Gustavo
Gustavo

Reputation: 1019

Access nested template types

Let's say there is a 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 template type int inside A?

Upvotes: 4

Views: 2547

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

Another method would be like 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

This way one can only instantiate A with instances of MyType.

If there's a need to instantiate A with any templated type, one uses a bit different specialisation:

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

This way, one can pass any templated type that doesn't have non-type template parameters.

Upvotes: 3

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Expose a type alias to the user:

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

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

Usage:

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

live example on wandbox

Upvotes: 6

Related Questions