2016-12-09 6 views
5

ためのstd :: enable_if:C++ - 私は機能を持っているより多くの種類の

template <typename T, 
    typename std::enable_if <std::is_same<T, int>::value == true>::type* = nullptr> 
void test(T i) 
{ 
    //process data 
} 

それは動作します。

しかし、intだけでなく、floatconst char *でもこの機能を有効にする必要があります...同じ方法を3回実行しないでこれを行うにはどうすればいいですか?このよう

答えて

10

template <typename T, 
    typename std::enable_if <std::is_same<T, int   >::value || 
          std::is_same<T, float  >::value || 
          std::is_same<T, const char *>::value>::type* = nullptr> 
void test(T i) 
{ 
    //process data 
} 
+0

1つの提案。恐らく、過負荷の選択において修飾子が重要でないならば、おそらく 'remove_cv'を使うことができます。 –

+0

@ YanZhouパラメータ 'i'は参照渡しではなく値渡しであるため、constnessと揮発性はとにかく削除されます。したがって、 'T'はCVで修飾されず、' remove_cv'はその型に対して何もしません。 –

2

C++ 17のための一般的なソリューション(godbolt.orgで確認)

#include <type_traits> 

template< typename U, typename ... Ts > struct belong_to 
{ 
    // before C++17 value will have to be defined recursively on the head of Ts 
    static constexpr bool value = (std::is_same< U, Ts >::value || ...); 
    using type = typename std::enable_if< value, U > ::type; 
}; 

// usage example: 
template< typename T > 
using testable = typename belong_to< T, int, float, const char >::type; 

template< typename T > void test (testable<T> i) 
{ 
    // test process 
} 

int main() 
{ 
    test< int  > (3); 
    test< float  > (3.0); 
    test< const char > ('c'); 
    // test< signed char >(1); does not compile!!! 
} 
1

別の一般的な解決策は、STDを使用することです::論理和(C++論理和を実行するために、指定可能な型は、テスト関数の呼び出しでテンプレートパラメータとして指定されるか、または特殊化のtypedefを定義できます。

#include <iostream> 
#include <type_traits> 

template <typename... Ts, typename T, typename std::enable_if<std::disjunction<std::is_same<T, Ts>...>::value>::type* = nullptr> 
void test(T i) 
{ 
    std::cout << "test\n"; 
} 

int main() 
{ 
    int i = 4; 
    test<int, float, const char*>(i); 
    //test<float, const char*>(i); // compile fails since no int 

    // or use a typedef for the specialization 
    typedef void (*specialized_t)(int); 
    constexpr specialized_t test2 = &test<int, float, const char*>; 
    test2(i); 
} 

run the code

関連する問題