谁能帮我理解为什么下面的代码不能编译:
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>
被转换到 wrapper< A<void >
使用 class wrapper
的转换运算符.
最佳答案
问题是 foo
-s 模板推导失败,因为隐式转换。
-
foo
试图推断类型 T - P =
wrapper<void>
, A =wrapper<A<T>>
-
foo
无法推断出什么A<T>
是
所以,我们得帮忙foo
推导出T。
解决方案一
让foo
明确知道 T 是什么:
foo<void>( wrapper<void>{} );
方案二
投 wrapper
至 wrapper< A<void> >
明确地让 foo
知道 T 是什么:
foo( static_cast< wrapper< A<void> > >(wrapper<void>{}) );
关于c++ - 尽管定义了强制转换运算符,但没有强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562972/