2

重複の可能性:
「template」および「typename」キーワードをどこに、なぜ配置する必要があるのですか?

「C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond」という本でテンプレート プログラミングを学んでいますが、どういうわけか最初の演習で行き詰まってしまいました。

タスクは、参照型の場合はを返し、それ以外の場合はadd_const_ref<T>を返す単項メタ関数を作成することです。TT 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 Unit Testing Frameworkを使用しているため、構文です):

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タイプであるという要件を満たさない理由が本当にわかりません。私が間違っていることのヒントをいただければ幸いです。

4

1 に答える 1

1

ここには多くの s がありません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;
};
于 2012-05-07T14:26:12.707 に答える