2012-05-07 6 views
2

可能性の重複:
Where and why do I have to put the “template” and “typename” keywords?メタ関数

私は著書「C++テンプレートメタプログラミング:ブーストと向こうからコンセプト、ツール、テクニック」でテンプレートプログラミングを学んでいますし、どういうわけか私は最初のエクササイズに立ち往生してしまった。

参照タイプの場合はTを返す単項メタ機能add_const_ref<T>を作成し、それ以外の場合はT const &を返します。

私のアプローチは次のとおりです。

template <typename T> 
struct add_const_ref 
{ 
    typedef boost::conditional 
     < 
     boost::is_reference<T>::value, // check if reference 
     T,        // return T if reference 
     boost::add_reference   // return T const & otherwise 
      < 
      boost::add_const<T>::type 
      >::type 
     >::type 
    type; 
}; 

私は(私はそれゆえ、構文をGoogleのユニットテストフレームワークを使用しています)それをテストしてみました:

TEST(exercise, ShouldReturnTIfReference) 
{ 
    ASSERT_TRUE(boost::is_same 
     < 
     int &, 
     add_const_ref<int &>::type 
     >::value 
    ); 
} 

しかし、それはコンパイルされません。

main.cpp:27:5: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct boost::add_reference’ 
main.cpp:27:5: error: expected a type, got ‘boost::add_const<T>::type’ 
main.cpp:28:4: error: template argument 3 is invalid 

なぜboost::add_const<T>::typeがタイプであるという要件を満たしていないのか、私は本当に分かりません。私は何が間違っているかのヒントに感謝します。

答えて

1

あなたはここにtypenameの多くの行方不明:このアウトを指し示すと、他のスレッドをリンクするための

template <typename T> 
struct add_const_ref 
{ 
    typedef typename boost::conditional 
    //  ^^^^^^^^ 
     < 
     boost::is_reference<T>::value, // check if reference 
     T,        // return T if reference 
     typename boost::add_reference   // return T const & otherwise 
    // ^^^^^^^^ 
      < 
      typename boost::add_const<T>::type 
    //  ^^^^^^^^ 
      >::type 
     >::type 
    type; 
}; 
+0

感謝を。 – nijansen

関連する問題