大佬教程收集整理的这篇文章主要介绍了c – 显式转换运算符模板的优先级和模糊性,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <iostream> #include <stdexcept> #include <cmath> using namespace std; class A { public: template<typename T> explicit operator T() const // 1 { cout << "operator T" << endl; return T(); } template<typename T> explicit operator const T&() const // 2 { cout << "operator const T&" << endl; throw runtime_error("operator const T&"); } template<typename T> explicit operator T&() // 3 { cout << "operator T&" << endl; throw runtime_error("operator T&"); } }; int main(int,char**) { try { const A& a = A(); cout << abs(static_cast<double>(a) - 3.14) << endl; } catch (const runtime_error&) { } return 0; }
我遇到的问题是为static_cast转换选择的运算符.对于海湾合作委员会来说,这是一种预期的(1)案例.输出是:
operator T 3.14
但Clang拒绝使用以下输出编译它:
@H_639_7@main.cpp:37:20: error: ambiguous conversion for static_cast from 'const A' to 'double' cout << std::abs(static_cast<double>(a) - 3.14) << endl; ^~~~~~~~~~~~~~~~~~~~~~ main.cpp:10:32: note: candidate function [with T = double] template<typename T> explicit operator T() const ^ main.cpp:16:32: note: candidate function [with T = double] template<typename T> explicit operator const T&() const ^ 1 error generated.
为什么Clang考虑转换(2),当它显然需要在转换序列中进行额外的构造函数调用时,而(1)不会?它是否正确(而GCC是错误的)这样做?
以上是大佬教程为你收集整理的c – 显式转换运算符模板的优先级和模糊性全部内容,希望文章能够帮你解决c – 显式转换运算符模板的优先级和模糊性所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。