Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested types of a template parameter T even if T is a pointer

Base structures:

struct Foo{
    typedef int inner_type;
};

template<class T>
struct Bar{
    typename T::inner_type x;
};

In main:

Bar<Foo>();  // Compiles OK
Bar<Foo*>(); // Doesn't compile: template T becomes a pointer-to-class and is not a valid class anymore. 

How to work around this?

like image 674
Patric Avatar asked Dec 06 '22 12:12

Patric


2 Answers

Specialize the Bar struct for a pointer-to-T type:

//non-specialized template for generic type T
template<class T>
struct Bar{
    typename T::inner_type x;
};

//specialization for pointer-to-T types
template<class T>
struct Bar<T*>{
    typename T::inner_type x;
};
like image 89
Jason Avatar answered Dec 09 '22 14:12

Jason


If you needed to do this in a situation where specializing the template would be awkward, you could also compute the type to use with some appropriate templates:

template<class T> struct remove_all_pointers {
    typedef T type;
};
template<class T> struct remove_all_pointers<T*> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* const> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* volatile> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* const volatile> {
    typedef typename remove_all_pointers<T>::type type;
};

struct Foo {
    typedef int inner_type;
};

template<class T>
struct Bar {
    typename remove_all_pointers<T>::type::inner_type x;
};
like image 45
Mankarse Avatar answered Dec 09 '22 15:12

Mankarse