Access to nested template types

Let's say there is class A and MyType

template<typename DataType>
class MyType {
...
}

template<typename MyType>
class A {
...
}

When I create an instance of A with A<MyType<int>>, how can I access the int template type inside A?

+4
source share
2 answers

Another way would be this:

template <typename DataType>
class MyType { ... };

template<typename X>            // template parameter name changed for clarity
class A;                        // intentionally left undefined

template<typename Y>
class A<MyType<Y>> { ...Y... }; // a specialisation

... A<MyType<int>> ...          // Y in the definition of A is int

Thus, an instance Acan only be created with instances MyType.

If you need to create an instance of A with any type template, then a bit of different specialization is used:

template<template<typename...> X, typename Y>
class A<X<Y>> { ...X<Y>... };   // a specialisation

... A<MyType<int>> ...          // X in the definition of A is MyType, Y is int
... A<OtherType<double>> ...    // X is OtherType, Y is double

Thus, any template type that does not have non-type template parameters can be passed.

+3
source

Print the user an alias of the type :

template<typename DataType>
class MyType {
public:
    using InnerDataType = DataType;
};

template<typename MyType>
class A {
public:
    using InnerType = MyType;
};

Using:

using MyA = A<MyType<int>>;
static_assert(std::is_same<
    typename MyA::InnerType::InnerDataType,
    int>{});

live example in wandbox

+6
source

Source: https://habr.com/ru/post/1671872/


All Articles