代码之家  ›  专栏  ›  技术社区  ›  zack

不接受变分模板函数参数

  •  1
  • zack  · 技术社区  · 1 年前

    以下代码无法构建,如有任何关于原因的反馈,我们将不胜感激。

    void bar(std::string str, int& a, int& b)
    {
    }
    
    template<typename T, typename ... Args>
    void foo(std::function<void(T, Args...)> fcn, Args ... args)
    {
        // Some code that calls fcn
    }
    
    void run()
    {
        int a = 3;
        int b = 5;
        foo<std::string, int&, int&>(bar, a, b);
    }
    

    它是对中提出的第一个解决方案的修改实现 this SO answer .

    IDE在调用行时给出以下错误 foo :

    C++模板<T班,班。。。Args>void foo(std::函数<void(T,Args…)>fcn,Args。。。args)

    没有函数模板“foo”的实例与参数列表匹配
    参数类型包括:
    (void(std::string str,int&a,int&b),int,int)

    单独测试,似乎通过了 fcn 使用模板参数的参数是可以的。问题似乎在于传递一个函数参数,该函数可以接受可变模板参数。

    2 回复  |  直到 1 年前
        1
  •  2
  •   Jarod42    1 年前

    函数(指针)不是 std::function ,所以不适用于扣减。

    你可以做 Ts... 在这种情况下是不可推断的

    template<typename T, typename ... Args>
    void foo(std::function<void(T, std::type_identity_t<Args>...)> fcn, Args ... args)
    {
        // Some code that calls fcn
    }
    

    Demo

    或下降 std::函数 完全地

    template<typename T, typename F, typename ... Args>
    requires (std::is_invocable<F, T, Args...>::value)
    void foo(F fcn, Args&& ... args)
    {
        // Some code that calls fcn
    }
    

    Demo

        2
  •  1
  •   serkan    1 年前
    • &当我删除它时,没有错误
    #include <iostream>
    #include <functional> 
    
    void bar(std::string str, int a, int b)
    {
    }
    
    template<typename T, typename ... Args>
    void foo(std::function<void(T, Args...)> fcn, Args ... args)
    {
        // Some code that calls fcn
    }
    
    
    int main() {
        std::function<void(std::string, int, int)> func_1 = bar;
        int a = 3;
        int b = 5;
        foo(func_1, a, b);
        return 0;
    }
    
    • 如果有必要使用Call by Reference,我尝试了直接提供地址,在这种情况下也有效。
    #include <iostream>
    #include <functional> 
    
    void bar(std::string str, int* a, int* b)
    {
    }
    
    template<typename T, typename ... Args>
    void foo(std::function<void(T, Args...)> fcn, Args ... args)
    {
        // Some code that calls fcn
    }
    
    
    int main() {
        std::function<void(std::string, int*, int*)> func_1 = bar;
        int a = 3;
        int b = 5;
        foo(func_1, &a, &b);
        return 0;
    }
    
    
        3
  •  1
  •   zack    1 年前

    谢谢大家。离开 answer by serkan 以下方法似乎奏效了。

    #include <iostream>
    #include <functional> 
    
    void bar(std::string str, int& a, int& b)
    {
    }
    
    template<typename T, typename ... Args>
    void foo(std::function<void(T, Args...)> fcn, Args ... args)
    {
        // Some code that calls fcn
    }
    
    int main() {
        std::function<void(std::string, std::reference_wrapper<int>, std::reference_wrapper<int>)> func_1 = bar;
        int a = 3;
        int b = 5;
        foo(func_1, std::ref(a), std::ref(b));
        return 0;
    }
    

    我会运行更多的测试,可能仍需要一些更改。