【发布时间】:2018-03-15 17:39:25
【问题描述】:
谁能帮我理解为什么下面的代码不能编译:
template< typename T >
class A
{};
template< typename U >
class wrapper
{
public:
// cast operator
operator wrapper< A<void> > ()
{
return wrapper< A<void> >{};
}
};
template< typename T >
void foo( wrapper< A<T> > )
{}
int main()
{
foo( wrapper<void>{} );
}
错误信息:
t.cpp:24:7: error: no matching function for call to 'foo'
foo( wrapper<void>{} );
^~~
t.cpp:18:10: note: candidate template ignored: could not match 'A<type-parameter-0-0>' against 'void'
void foo( wrapper< A<T> > )
^
1 error generated.
以及如何解决?
我预计 wrapper<void> 使用 class wrapper 的转换运算符转换为 wrapper< A<void >。
【问题讨论】:
-
修复它执行显式静态强制转换,因此模板参数推导将获得正确的类型。您似乎假设模板参数扣除将考虑可能的用户定义的转换。
标签: c++ templates casting typecast-operator