Reputation: 169
template<typename HELPER_>
class A{
public:
typedef HELPER_ HELPER ;
typedef typename HELPER::TRAITS_ TRAITS_2;
// other stuff....
};
My question is that HELPER_
is a type , then HELPER
will also be a type, then what does HELPER::TRAITS
_ signify. similarly if HELPER
is not the name of class, it is just an unknown type being specified. But in the above code it feels like HELPER
is the name of the class and it is calling its public variable name TRAITS_
.
I want to know what the above code means.
Upvotes: 1
Views: 155
Reputation: 96241
The code is allowing you to specify customized traits in the template class by using a separate class to specify those traits. It uses typedef to help complete the abstraction. For example, you could set up a trait class so that A::TRAITS_
works out to be int
like this (noting that type names in all caps with a trailing underscore are somewhat uncommon):
class MyTraits
{
public:
typedef int TRAITS_;
};
template<typename HELPER_>
class A{
public:
typedef HELPER_ HELPER ;
typedef typename HELPER::TRAITS_ TRAITS_2;
// other stuff....
};
// A<MyTraits>::TRAITS_2 is now `int`.
Upvotes: 1
Reputation: 131789
TRAITS_
is a nested name inside whatever HELPER_
happens to be. Since typename
is put in front of this nested name, it's expected to signify a type.
Example:
#include <string>
#include <iostream>
template<class T>
struct X{
typedef typename T::some_type some_type;
X(some_type const& p)
: m(p) {}
private:
some_type m;
};
struct A{
typedef int some_type;
};
struct B{
typedef std::string some_type;
};
int main(){
X<A> x1(5);
X<B> x2("hi");
std::cout << "X<A>::m = " << x1.m << ", X<B>::m = " << x2.m "\n";
}
Output:
X<A>::m = 5, X<B>::m = hi
Upvotes: 0
Reputation: 63765
This code is assuming that for any HELPER_
template parameter used, HELPER_::TRAITS_
exists and is a typename.
What the code is actually doing:
For a type X
, this code is establishing that A<X>::TRAITS_2
is defined as the same type as X::TRAITS_
Upvotes: 1
Reputation: 15278
typedef HELPER_ HELPER ;
Aliases HELPER_
as HELPER
in class namespace, so A<B>::HELPER
becomes equivalent to B
. It can useful in template code.
typedef typename HELPER::TRAITS_ TRAITS_2;
Aliases HELPER::TRAITS
_ as TRAITS_2
in class namespace, so A<B>::TRAITS_2
becomes equivalent to B::TRAITS_
. typename
is necessary, becouse compiler doesn't know that HELPER::TRAITS_
is a type without definition of HELPER.
Upvotes: 1