C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 显式转换运算符模板的优先级和模糊性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在我的项目中使用模板化的显式转换运算符,以实现类似自定义变体类型的显式转换.再现我的问题的最小示例如下所示(在C 14模式下):

#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是错误的)这样做?

解决方法

static_cast执行隐式转换或直接初始化.在你的情况下,隐式转换是不可行的,但直接初始化是因为Static_castexplicit constructors and conversion functions.所以我的猜测是clang(在我看来正确)确定有两种可能的直接初始化和抱怨.不知道GCC内部发生了什么,也许它认为操作符T(),如果它可以找到一个,无论是否存在其他的.

大佬总结

以上是大佬教程为你收集整理的c – 显式转换运算符模板的优先级和模糊性全部内容,希望文章能够帮你解决c – 显式转换运算符模板的优先级和模糊性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。