views:

60

answers:

1

hi

I am trying to use type traits to add reference to a template parameter.

template < class T >
struct S {
typename add_reference< T >::type reference; // reference member should always be a reference
};
...
typedef Bar< Foo > type;
S< type > s; // does not add reference, S:: reference is of type type, not type&

However it does not seem to work. is it the right way to do it? my compiler is g++ 4.3. thanks.

clarification: I have would like reference member to be reference, regardless if S< type > or S< type& > is instantiated.

+7  A: 

You forgot typedef. The typename just says that you are going to use a typename that at the point of the template declaration is not yet known as a type. If you actually want to create a typedef, you actually need that keyword in addition. And i think you forgot to actually name the type when you use it below:

template < class T >
struct S {
  typedef typename add_reference< T >::type reference;
};
...
typedef Bar< Foo > type;
S< type >::reference s = some_foo; // initialize!

Remember to initialize the reference. If you know in advance that T is never a reference (to avoid the reference-to-reference problem) you can also do this directly:

template < class T >
struct S {
  typedef T &reference;
};

typedef Bar< Foo > type;
S< type >::reference s = some_bar_foo; // initialize!

If what you wanted to do is to create a reference data member, your syntax without typedef was correct

template < class T >
struct S {
  typename add_reference< T >::type reference;
};
...
typedef Bar< Foo > type;
S< type > s = { some_bar_foo }; // initialize!
s.reference = some_other_bar_foo; // assign "some_other_bar_foo" to "some_bar_foo"

I do not know what you want to do exactly.

Johannes Schaub - litb
oh yes, i hadn't seen the missing "typedef". That too, of course :)
Benoît
aaa