Почему ни один из этих шаблонов функций не совпадает с инстанциями?

StackOverflow https://stackoverflow.com//questions/12690631

Вопрос

Следующий код не может компилировать с Intel 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» - это аргумент шаблона по умолчанию .И это не работает в вашем случае, потому что эта функция не перегружена.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top