c++ - 模板转换运算符问题

标签 c++ templates type-conversion implicit-conversion

我进行了一些浏览,这是最相关的 link我可以找到,但它没有回答我的问题

问题:为什么模板替换失败,以下内容无法编译?

template <typename T>
struct A
{
   A() {};
   A(T value) : val(value){} 
   operator T() { return this->val;}
   T val;
};


A<std::string> test;
std::cout << "xxx" + std::string(test); //works fine
std::cout << "xxx" + test; //compiler error

错误消息:

error: no match for 'operator+' (operand types are 'const char [4]' and 'A<std::__cxx11::basic_string<char> >')
   19 |    std::cout << "xxx" + test;
      |                 ~~~~~ ^ ~~~~
      |                 |       |
      |                 |       A<std::__cxx11::basic_string<char> >
      |                 const char [4]

最佳答案

std::operator+(std::basic_string) 是一组运算符模板,需要对第二个操作数进行模板实参推导test 。但 template argument deduction 中不会考虑隐式转换(从 A<std::string>std::string ) .

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

正如您所展示的,显式转换如 "xxx" + std::string(test);工作正常。您还可以显式指定模板参数(以丑陋的方式)来绕过模板参数推导。

operator+ <char, std::char_traits<char>, std::allocator<char>>("xxx", test);

关于c++ - 模板转换运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68829565/

相关文章:

c++ - 是否可以简化这些 C++ 模板参数?

c++ - 为什么总和为0?

python - 如何从Python数据框中的DateTimeIndex中删除微秒?

C# WinForms - 自动添加两个文本框

c++ - 为什么缩小不影响重载分辨率?

c++ - 返回值优化和构建结构的函数

python - super 简单并且可以使用现有 Django 身份验证系统的最佳 Django 应用程序/论坛是什么?

F# int64 到 int

c++ - 什么是结构的非成员?

c++ - 如何在 C/C++ 中关闭特定客户端的套接字?