用于从嵌套类型中提取模板参数的类型特征
Type trait for extracting template parameter from nested type
我需要从嵌套类型中获取模板参数。这是一个简单的例子来显示我需要提取的类型。
#include <iostream>
#include <typeinfo>
template<typename T>
void function(T) {
// T = 'struct A<int>::B'
//
// Here I want to get the template value type e.g. 'int' from T
// so that this would print 'int'. How can this be done?
std::cout << typeid(T).name() << std::endl;
}
template<typename T>
struct A {
using B = struct { int f; };
};
int main() {
function(A<int>::B{});
return 0;
}
你不能通过简单的推导来提取这个。虽然 B
是 A
的嵌套 class,但类型本身是不相关的。
一个选项是 "save" B
中的类型,稍后提取它:
template<typename T>
struct A {
struct B {
using outer = T;
int f;
};
};
然后你就用typename T::outer
得到类型:
template<typename T>
void function(T) {
std::cout << typeid(typename T::outer).name() << std::endl;
}
我需要从嵌套类型中获取模板参数。这是一个简单的例子来显示我需要提取的类型。
#include <iostream>
#include <typeinfo>
template<typename T>
void function(T) {
// T = 'struct A<int>::B'
//
// Here I want to get the template value type e.g. 'int' from T
// so that this would print 'int'. How can this be done?
std::cout << typeid(T).name() << std::endl;
}
template<typename T>
struct A {
using B = struct { int f; };
};
int main() {
function(A<int>::B{});
return 0;
}
你不能通过简单的推导来提取这个。虽然 B
是 A
的嵌套 class,但类型本身是不相关的。
一个选项是 "save" B
中的类型,稍后提取它:
template<typename T>
struct A {
struct B {
using outer = T;
int f;
};
};
然后你就用typename T::outer
得到类型:
template<typename T>
void function(T) {
std::cout << typeid(typename T::outer).name() << std::endl;
}