我们假设有一个A类和MyType
template<typename DataType>
class MyType {
...
}
template<typename MyType>
class A {
...
}
当我使用A<MyType<int>>
创建A的实例时,如何在A中访问模板类型int?
答案 0 :(得分:6)
向用户公开type alias:
template<typename DataType>
class MyType {
public:
using InnerDataType = DataType;
};
template<typename MyType>
class A {
public:
using InnerType = MyType;
};
用法:
using MyA = A<MyType<int>>;
static_assert(std::is_same<
typename MyA::InnerType::InnerDataType,
int>{});
答案 1 :(得分:3)
另一种方法是这样的:
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
这样,人们只能使用A
的实例MyType
进行实例化。
如果需要使用任何模板化类型实例化A,则使用不同的专业化:
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
这样,可以传递任何没有非类型模板参数的模板类型。