Reputation: 3801
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:
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
?
Upvotes: 0
Views: 388
Reputation: 56863
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.
Upvotes: 6