これらの関数テンプレートのどちらもインスタンス化と一致しないのですか?

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