c++ - 尽管定义了强制转换运算符,但没有强制转换

标签 c++ templates casting typecast-operator

谁能帮我理解为什么下面的代码不能编译:

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>{} );

方案二

wrapperwrapper< A<void> >明确地让 foo知道 T 是什么:

foo( static_cast< wrapper< A<void> > >(wrapper<void>{}) );

关于c++ - 尽管定义了强制转换运算符,但没有强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562972/

相关文章:

serialization - 在 Scalding 中读写案例类

c++ - 无法捕获异常

C++ boost asio |同步写入到异步读取 |无法在第二次读取中接收到正确的数据

c++ - 从依赖基类访问类型

python - 如何在 python 魔术编码说明符行中指定扩展的 ascii(即 range(256))?

c++ - 令人困惑的 (*this) 指针转换

c++ - 删除指针的时间

c++ - 使用原始输入同时获取两只老鼠的数据

c++ - 调试打印解压缩可变参数模板函数参数

C# 将 `int[]` 数组就地转换为 `byte[]` 数组