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?
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;
};
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With