我有以下模板:
template<typename T, const char *name_ >
struct named {
typedef T type;
static constexpr const char *name = name_;
};
我想要的类型特征是:
- 如果参数类型是“named”,将提取类型和名称(2 个不同)
- 如果参数不同,将提取原始类型和空字符串 类型。
例子:
template<typename T>
void foo() {
typename cppdi::extract_type<T>::type x;
std::cout << "type: " << typeid(x).name() <<
", name: " << cppdi::extract_name<T>::value << std::endl;
}
char bar[] = "bar";
void test() {
foo<int>(); // type: i, name:
foo<named<int, bar>>(); // type: i, name: bar
}
是否可以实现这样的extract_type
和extract_name
?
最佳答案
这样写你的特质:
template< typename T >
struct extract_type
{ using type = T; };
template< typename T, const char* S >
struct extract_type< named< T, S > >
{ using type = T; };
template< typename T >
struct extract_name
{ static constexpr const char* value = ""; };
template< typename T, const char* S >
struct extract_name< named< T, S > >
{ static constexpr const char* value = S; };
仅此一项是行不通的,您提供的代码在多个地方都是非法的。我在这个 live example 中修复了它们.
关于C++ 类型特征提取模板参数的特化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26787099/