【发布时间】:2021-08-18 09:13:02
【问题描述】:
我浏览了一下,这是我能找到的最相关的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]
【问题讨论】:
-
不是替换失败。请在问题中包含错误消息
-
Fwiw,
static_cast在这里可以工作,因为它不仅考虑隐式转换(在这里会失败),而且还考虑直接初始化 和 转换函数(这将工作这里)。 IE。"xxx" + static_cast<std::string>(test)应该成功。 -
谢谢@WhozCraig。有没有办法修复模板以适应这种情况?
-
@eucristian Meh。并不真地;至少我不想在代码中写上我的名字。
operator +的模板好友重载与operator <<的好友重载相结合可以做到这一点,但天哪。后者可以通过@songyuanyao 在他的回答评论中显示的方法来避免。
标签: c++ templates type-conversion implicit-conversion