使用SFINAE启用转换运算符

Ste*_*mer 9 c++ templates sfinae type-traits enable-if

我正在尝试operator T()使用SFINAE 重载以在T基本类型时返回副本,并在T类时使用const引用.

double下面的示例中使用a 时,我无法std::is_class删除第二个重载(with ).

也就是说,我得到的错误是:

error: no type named ‘type’ in ‘struct std::enable_if<false, const double&>’
operator typename std::enable_if< std::is_class<T>::value, const T&>::type () const
^
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

#include <iostream>
#include <type_traits>

template<typename T>
struct Foo
{
    operator typename std::enable_if<!std::is_class<T>::value, T >::type () const
    {
        return _val;
    }

    operator typename std::enable_if< std::is_class<T>::value, const T&>::type () const
    {
        return _val;
    }

    T _val;
};

int main()
{
    Foo<double> f1;
    f1._val = 0.3;

    double d = f1;
    std::cout << d << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 11

T在您的类成员函数被实例化时已经知道,因此不会发生替换,而不是SFINAE,您会收到一个硬错误.最简单的解决方法是为这些运算符重载引入虚拟模板参数,并将其默认为T仍然可以进行类型推导.

template<typename U = T>
operator typename std::enable_if<!std::is_class<U>::value, U >::type () const
{
    return _val;
}

template<typename U = T>
operator typename std::enable_if< std::is_class<U>::value, const U&>::type () const
{
    return _val;
}
Run Code Online (Sandbox Code Playgroud)

现场演示


Ste*_*mer 5

虽然没有解决为什么不正确的运算符没有被丢弃的问题,但为了解决手头的特定问题,即对于类类型按 const ref 返回或对于其他类型按值返回,可以使用std::conditional.

template< bool B, class T, class F >
struct conditional;
Run Code Online (Sandbox Code Playgroud)

提供成员 typedef 类型,如果 B 在编译时为真,则定义为 T,如果 B 为假,则定义为 F。

工作示例:

#include <iostream>
#include <type_traits>

template<typename T>
struct Foo
{
    operator typename std::conditional<
        std::is_class<T>::value, const T&, T>::type () const
    {
        return _val;
    }

    T _val;
};

int main()
{
    Foo<double> f1;
    f1._val = 0.3;

    double d = f1;
    std::cout << d << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)