SFINAE:std :: enable_if作为函数参数

问题描述 投票:8回答:2

因此,我遵循此网页上某处代码所设置的示例: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

c++ templates c++11 sfinae
2个回答
12
投票

示例是错误的,因为T中的non-deduced context


1
投票

为了允许推论,您需要一个直接基于T的函数参数。然后,您需要弄清楚enable_if的放置位置(实际上,这不允许推导T)。常用选项位于返回类型或您忽略的其他默认参数上。

© www.soinside.com 2019 - 2024. All rights reserved.