이러한 함수 템플릿 중 하나가 인스턴스화와 일치하지 않는 이유는 무엇입니까?

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