简体   繁体   中英

C++ type trait to extract specialization value of template argument

I have following template:

template<typename T, const char *name_ >
struct named {
  typedef T type;
  static constexpr const char *name = name_;
};

I'd like to have type traits which:

  • would extract type and name (2 different) if argument type is "named"
  • would extract original type and empty string if argument is different type.

Example:

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
}

Is it possible to implement such extract_type and extract_name ?

Write your traits like this:

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; };

That alone won't work, the code you gave is illegal in several places. I fixed them in this live example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM