为什么这个简单的代码不起作用?
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)
问题出在哪儿?
你依赖于函数参数的模板参数推导.但是无法推导出函数模板参数,因为这是一个不可推导的上下文.
更具体地说,U即使retype<U>::type是,也不能推导出模板参数int.因为可能有一个特化retype定义为:
template<>
struct retype<X>
{
typedef int type;
};
Run Code Online (Sandbox Code Playgroud)
所以你看,给定的retype<U>::type是int模板参数U也可以X.
事实上,可能有不止一个这样的专业化,所有这些专业化都可以定义type为int.所以没有一对一的关系.编译器无法唯一推导出U.
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |