2

I've got the following situation:

This is a wrapper type

template <typename wrapperInnerType>
struct wrapperT{ ... };
using wrapper = wrapperT<float>;

And it's used in this class

template <typename wrapperType>
class InData{
    wrapperInnerType var;   //<-- How to get inner type?
};

My question is what is the easiest way to get wrapperInnerType from wrapperType?

Ideally I would like it to be still possible to use InData<wrapper> myData; when using that class (instead of having multiple types in declaration like in InData<wrapper, float> myData; as an example).

Shrimp
  • 514
  • 5
  • 9
  • Does this answer your question? [How can I get the innermost template parameter type?](https://stackoverflow.com/questions/25187323/how-can-i-get-the-innermost-template-parameter-type) – NutCracker Jan 27 '20 at 09:53

2 Answers2

4

The easiest way is to define a type alias in wrapperT.

template <typename wrapperInnerType>
struct wrapperT {
    using innerType = T;
    // ...
};
using wrapper = wrapperT<float>;

template <typename wrapperType>
class InData{
    typename wrapperType::innerType var;
};

Another approach could be to make a helper struct that extract it using a template template parameter and partial specialization. This would avoid having to modify wrapperT and could potentially give some re-usability. The template signature of wrap would however have to be known for this to work.

template <typename T>
struct getInnerType;

template <template <typename> typename wrap, typename Inner>
struct getInnerType<wrap<Inner>> {
    using type = Inner;
}

template <typename T> // For more convenient use as pointed out in comments
using getInnerType_t = typename getInnerType<T>::type

template <typename wrapperType>
class InData{
    getInnerType_t<wrapperType> var;   //<-- How to get inner type?
};
super
  • 12,335
  • 2
  • 19
  • 29
3

You could declare the following class template, wrapper_inner_type:

template<typename>
struct wrapper_inner_type;

Then, specialize it for the wrapper, wrapperT<InnerType>, where InnerType is the type you want to find out:

template<typename InnerType>
struct wrapper_inner_type<wrapperT<InnerType>> {
   using type = InnerType;
};

You can also define this alias template for convenience:

template<typename T>
using wrapper_inner_type_t = typename wrapper_inner_type<T>::type;

Finally, in order to get the inner type inside InData:

template <typename wrapperType>
class InData{
    wrapper_inner_type_t<wrapperType> var;
};
JFMR
  • 23,265
  • 4
  • 52
  • 76