c++ - 隐式类型转换编译失败,这是为什么?

标签 c++ string templates implicit

我写了一段小代码:

#include<type_traits>

using namespace std;

template<typename T>
struct M{
    /*explicit*/ M(const T*) {}
};

template<typename T>
M<T> f(const M<T>&) {return M<T>();}

int main() {
    M<char> s1 = f<char>("Hello"); // OK
    M<char> s2 = f("Hello"); // error
    M<char> s3 = f(decay<char*>("Hello")); // error
    return 0;
}

嗯第一个s1成功编译,尽管如果我更改 M::M要显式,它也会失败。但是s2s3无法编译,即使我使用 decay<char*>s3 .


区别在于我是否为 f 指定了模板初始化参数类型或不。为什么s2s3编译失败,C++标准有什么原则吗?

如果我将 main 函数改成这样:

int main()
{
    M<char> s1=f<char>("Hello");//OK
    const char* p="hello";
    M<char> s2=f(p);//error
    M<char> s3=f(decay<const char*>("Hello"));//error
    return 0;
}

还是失败了。

为什么?

最佳答案

因为 template type argument deduction不考虑隐式转换。

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

对于第二种情况,编译器无法匹配M<T>const char [6] ,函数模板在重载决议之前被忽略。

第三个案例失败,因为"Hello" (即 const char [6] )无法转换为 decay<char *> .你可能是说 typename decay<char*>::type , 但由于与第二种情况相同的原因,它仍然无法编译。

关于c++ - 隐式类型转换编译失败,这是为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38088938/

相关文章:

c++ - 收集 Visual Studio IntelliSense 错误并通过脚本将它们转储到文本文件?

c++ - 内联函数体的替换何时执行

c++ - Qt QFileDialog::setDirectory 在 Ubuntu 12.04 中的有趣行为

ruby-on-rails - 来自数组的 RoR 字符串

c++ - C2061 'string' : undeclared identifier

c++ - Exe 在 BackupRead Windows 函数中崩溃

c - 如何使用宏中定义的字符串/将其转换为整数?

c++ - 编译模板

c++ - 模板的模板的参数类型推导规则是什么?

c++ - 为什么派生模板类不能访问基模板类的标识符?