2016-03-28 6 views
0

を推論:(この質問は約C++ 14である)テンプレートパラメータの型推論ルールを使用して、次のコードでは、関数テンプレートパラメータの正確なタイプ

#include <iostream>  

template <typename T> 
void test(T x) 
{ 
     std::cout << "T x" << std::endl; 
} 

template <> 
void test<int>(int x) 
{ 
     std::cout << "int x" << std::endl; 
} 

template <> 
void test<int &>(int &x) 
{ 
     std::cout << "int &x" << std::endl; 
} 

int main() 
{ 
     int x = 5; 
     int &y = x; 

     test(x); 
     test(y); 

     return 0; 
} 

ルールが明確es explained, for example, here(参照が破棄された状態)、出力は

int x 
int x 

となり、最も一致するオーバーロードとして非常に期待されます。しかし場合によっては、出力は

int x 
int &x 

が望ましい場合があります。直感的には、パラメータの正確な型は何かを推論するためのテンプレート引数型の控除の方法はありますか?

+0

?コンパイラは直感的に動かない –

+0

私はあなたが何を求めているのかわからないが[この最近のスレッド](http://stackoverflow.com/questions/36050087/how-to-distiguish-between-an-rvalue - と - rvalue-reference-in-a-function-parameter /)は役立ちます –

答えて

3

引数の宣言型を渡す必要があります。構文的ハードルを乗り越えるために、このマクロを使用します。

namespace detail{ 
    template <typename T> void test(T){std::cout << "T" << std::endl;} 
    template <> void test<>(int){std::cout << "int" << std::endl;} 
    template <> void test<>(int&){std::cout << "int&" << std::endl;} 
} 

#define TEST(x) detail::test<decltype(x)>(x) 

今、単純に引数を指定して呼び出す:あなたが最後の文で、「直感的に」とはどういう意味ですか

TEST(x) // int 
TEST(y) // int&