2

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

I am learning template programming by the book "C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond" and somehow I got myself stuck at the very first exercise.

The task is to write an unary metafunction add_const_ref<T> that returns T if it is a reference type, and otherwise returns T const &.

My approach is:

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;
};

I tried to test it (I am using the Google Unit Testing Framework, hence the syntax):

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

But it does not compile:

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

I really don't understand why boost::add_const<T>::type would not meet the requirement of being a type. I would appreciate a hint what I am doing wrong.

Community
  • 1
  • 1
nikolas
  • 8,707
  • 9
  • 50
  • 70

1 Answers1

1

You're missing a lot of typenames here:

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;
};
Xeo
  • 129,499
  • 52
  • 291
  • 397