得到了GCC的"无匹配功能"

use*_*152 4 c++ templates

为什么这个简单的代码不起作用?

template<class U>
class retype 
{ 
    typedef U type; 
};

class object
{
public:
    template<class U>
    int create(typename retype<U>::type p)
    {
        return 4;
    }
};

int main()
{
    int n = object().create(5);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在使用GCC进行编译时出现此错误:

test.cpp: In function ‘int main()’:
test.cpp:20: error: no matching function for call to ‘object::create(int)’
Run Code Online (Sandbox Code Playgroud)

问题出在哪儿?

Naw*_*waz 5

你依赖于函数参数的模板参数推导.但是无法推导出函数模板参数,因为这是一个不可推导的上下文.

更具体地说,U即使retype<U>::type是,也不能推导出模板参数int.因为可能有一个特化retype定义为:

template<>
struct retype<X>
{
      typedef int type;
};
Run Code Online (Sandbox Code Playgroud)

所以你看,给定的retype<U>::typeint模板参数U也可以X.

事实上,可能有不止一个这样的专业化,所有这些专业化都可以定义typeint.所以没有一对一的关系.编译器无法唯一推导出U.

  • @ user1941152:对于演绎,你必须走另一个方向.`retype <U> :: type`应该是`int`.什么是'U`?那么,你必须检查`retype`的每一个特殊化.所以语言设计师只是说演绎不会以这种方式发生. (2认同)