区分转换运算符模板以用于引用和非引用类型

时间:2016-07-05 23:41:17

标签: c++ templates c++11 gcc conversion-operator

我有一个struct InferValueType,它可以隐式转换为任何其他类型,包括引用类型。我使用以下代码完成此操作。

struct InferValueType {
    // ...

    template <typename Type>
    operator Type() const && {
        // ...
    }

    // We need this special version to allow conversions to reference types
    template <typename Type>
    operator Type&() const & {
        // ...
    }
};

InferValueType永远不会被用户实例化,而是将其作为函数的返回值提供。

const InferValueType read();

InferValueTyperead的组合允许用户编写如下的惰性代码:

int i = read();
MyType t1 = read();
MyType& t2 = read();
const MyType& t3 = read();

我已经对GCC 4.8,4.9,5,6和Clang 3.7和3.8进行了测试。只有GCC 4.8抱怨模棱两可。

conversion from ‘const InferValueType’ to ‘int’ is ambiguous
conversion from ‘const InferValueType’ to ‘MyType’ is ambiguous

我认为这是因为intMyType可以分别使用const int&const MyType&构建。

问题:在4.9.2之前,这是GCC的特点还是在C ++ 11下实际上是歧义?

完整的示例是here

0 个答案:

没有答案