为什么这些函数模板中的任何一个都与实例化不匹配?

Why don't either of these function templates match the instantiations?

本文关键字:实例化 不匹配 任何一 函数模板 为什么      更新时间:2023-10-16

以下代码无法使用英特尔C++ 2013 进行编译。

#include <type_traits>
#include <iostream>

template <
    typename T, 
    typename std::enable_if<std::is_integral<T>::value>::type
>
void myfunc( T a) 
{ 
    std::cout << a << std::endl;
}
template <
    typename T, 
    typename std::enable_if<!std::is_integral<T>::value>::type
>
void myfunc( T a) 
{ 
    std::cout << a << std::endl;
}


int main()
{
    double a;
    int b;
    myfunc(a);
    myfunc(b);
    return 0;
}

下面是错误输出:

ConsoleApplication1.cpp(33): error : no instance of overloaded function "myfunc" matches the argument list
1>              argument types are: (double)
1>      myfunc(a);
1>      ^
1>  
1>ConsoleApplication1.cpp(34): error : no instance of overloaded function "myfunc" matches the argument list
1>              argument types are: (int)
1>      myfunc(b);
1>      ^
1>  

我哪里出错了?

在函数中使用 enable_if 的通常和正确的方法是将其粘贴在返回类型中。

template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type myfunc(T a) {
    std::cout << a << " (integral)" << std::endl;
}
template <typename T>
typename std::enable_if<!std::is_integral<T>::value>::type myfunc(T a) {
    std::cout << a << " (non-integral)" << std::endl;
}

对于您的变体,正确的方法是:

template <typename T,
          typename = typename std::enable_if<std::is_integral<T>::value>::type>
void myfunc(T a) {
    std::cout << a << " (integral)" << std::endl;
}

。"enable_if"是默认模板参数。它在您的情况下不起作用,因为该功能没有过载。