SFINAE:std :: enable_if作为函数参数 [英] SFINAE: std::enable_if as function argument

查看:75
本文介绍了SFINAE:std :: enable_if作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我遵循此网页上某处代码设置的示例:
http://eli.thegreenplace.net/2014/sfinae-and-enable_if/

So, I'm following the example set by the code somewhere on this web page: http://eli.thegreenplace.net/2014/sfinae-and-enable_if/

这里是我所拥有的:

template<typename T>
void fun(const typename std::enable_if_t<std::is_integral<T>::value, T>& val) {
    std::cout << "fun<int>";
}

template<typename T>
void fun(const typename std::enable_if_t<std::is_floating_point<T>::value, T>& val) {
    std::cout << "fun<float>";
}

int main()
{
    fun(4);
    fun(4.4);
}

这种方式我必须写:

fun<int>(4);
fun<double>(4.4);

如何避免这种情况?

编译器抱怨无法推断出参数 T

Compiler complains that it can't deduce the parameter T.

推荐答案

这些示例是错误的,因为 T 非推论情境。除非您调用 fun< int>(4); 之类的函数,否则代码不会编译,但这可能不是作者想要显示的。

The examples are wrong, since T is in a non-deduced context. Unless you call the function like fun<int>(4);, the code won't compile, but this is probably not what the author intended to show.

正确用法是允许编译器推断 T 并将SFINAE条件放在其他位置,例如,使用返回类型语法:

The correct usage would be to allow T to be deduced by the compiler, and to place a SFINAE condition elsewhere, e.g., in a return type syntax:

template <typename T>
auto fun(const T& val)
    -> typename std::enable_if<std::is_integral<T>::value>::type
{
    std::cout << "fun<int>";
}

template <typename T>
auto fun(const T& val)
    -> typename std::enable_if<std::is_floating_point<T>::value>::type
{
    std::cout << "fun<float>";
}

演示

此外, typename s在您的代码中与 std :: enable_if_t 的用法相矛盾。

Also, the typenames in your code contradict your usage of std::enable_if_t.

请使用< a href = / questions / tagged / c%2b%2b11 class = post-tag title =显示已标记 c ++ 11的问题 rel = tag> c ++ 11 :

typename std::enable_if<...>::type

std::enable_if_t<...>








在没有返回类型的构造函数中如何工作? SFINAE条件可以隐藏在模板参数列表中:

In case of constructors, the SFINAE condition can be hidden in a template parameter list:

struct A
{    
    template <typename T,
              typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
    A(const T& val)
    {
        std::cout << "A<int>";
    }

    template <typename T,
              typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
    A(const T& val)
    {
        std::cout << "A<float>";
    }
};

DEMO 2

或者,在,您可以使用以下概念:

Alternatively, in c++20, you can use concepts for that:

A(const std::integral auto& val);

A(const std::floating_point auto& val);

这篇关于SFINAE:std :: enable_if作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆