C++ 类型特征提取模板参数的特化值

标签 c++ c++11 typetraits

我有以下模板:

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_typeextract_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/

相关文章:

c++ - 使用DirectX重制Star Fox

c++ - 自定义字节大小?

C++11 模板,确定返回类型

c++ - 在 for 循环中使用科学记数法

java - 适用于交互式移动 map 的语言/框架

C++11 如何使用 lambda 和高阶函数将 vector 转换为不同类型的 vector

c++ - 无法将 'std::ostream {aka std::basic_ostream<char>}' 左值绑定(bind)到 'std::basic_ostream<char>&&'

c++ - std::is_trivially_copyable 错了吗?

c++ - 如何调试由类型特征引起的这个错误?