小编nsh*_*lov的帖子

函数模板参数推导(类与功能模板)

你能帮我理解为什么参数推导适用于类模板而不适用于函数模板?

如果我理解正确,类模板定义了一个函数,所以当我调用它时,编译器可以进行隐式转换,但是在函数模板的情况下,目前没有函数定义,所以隐式转换没有发生.

但是我不明白为什么编译器不能创建函数定义然后应用隐式转换?

#include <functional>

template<typename ...ARGS>
class Test1
{
public:
    void add(const std::function<void(ARGS...)>&) {}
};

class Test2
{
public:
    template<typename ...ARGS>
    void add(const std::function<void(ARGS...)>&) {}
};

void func(int) {}

int main()
{
    Test1<int> test1;
    test1.add(func);

    Test2 test2;
    test2.add<int>(func);
}
Run Code Online (Sandbox Code Playgroud)

错误是:

在函数'int main()'中:

   25:24:错误:没有匹配函数来调用'Test2 :: add(void(&)(int))'

   25:24:注意:候选人是:

   14:10:注意:模板void Test2 :: add(const std :: function&)

   14:10:注意:模板参数扣除/替换失败:

   25:24:注意:不匹配的类型'const std :: function'和'void(int)'

c++ templates std-function template-argument-deduction argument-deduction

10
推荐指数
1
解决办法
289
查看次数