更新时间:2022-10-15 17:43:15
首先,让我们称其为 value_type
而不是 base
,因为 value_type
似乎更适合描述您要提取的类型.
你可以使用这个:
templatestruct extract_value_type//我们称之为extract_value_type{typedef T value_type;};模板X 类,类型名称 T>struct extract_value_type<X<T>>//专业化{typedef T value_type;};
只要 extract_value_type
的模板参数是 T
或 X
的形式,它就应该可以工作.但是,它不适用于 X
.但是使用可变参数模板在 C++11 中很容易实现它.
将其用作:
template 结构我的模板{typedef typename extract_value_type::value_type value_type;};
现在在 C++11 中,您可以使用可变参数模板使 extract_value_type
与接受多个模板参数的类模板一起使用,例如 std::vector
、std::set
、std::list
等
template类 X,类型名称 T,类型名称 ...Args>struct extract_value_type//专业化{typedef T value_type;};
In a template, I want to drill down the template parameter to the real non-templated type. So:
template <typename T>
struct MyTemplate
{
// sadly there's no extract_Base
typedef typename extract_base<T>::MyType WorkType;
};
struct X {};
template <typename T> struct Templ {};
//MyTemplate<Templ<X>>::WorkType is X;
//MyTemplate<X>::WorkType is X;
The only solution I see is to define real base type like std::vector<X>::value_type is X. But I am curious if there's a way to do this without defining auxiliary types inside each destination template.
I saw something like http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2965.html but this is draft? and I don't quite get it.
Yes I know there's multiple inheritance, but even for simple case this would be nice.
UPDATE: Nawaz solution works for me very well, and it is easy to extend to specific cases, e.g.
template<template<typename, typename> class X, typename T1, typename T2>
struct extract_base <X<T1, T2>> //specialization
{
typedef T1 base;
};
I can even apply is_base_of or other filters to T1/T2 and so on. So it does work for X<T,U> - at least with g++ 4.6.7.
First of all, let's call it value_type
instead of base
, because value_type
seems to be more appropriate term to describe the type which you want to extract.
You can use this:
template<typename T>
struct extract_value_type //lets call it extract_value_type
{
typedef T value_type;
};
template<template<typename> class X, typename T>
struct extract_value_type<X<T>> //specialization
{
typedef T value_type;
};
It should work as long as the template argument to extract_value_type
is of the form of either T
or X<T>
. It will not work for X<T,U>
, however. But then it is easy to implement it in C++11 using variadic template.
Use it as:
template <typename T>
struct MyTemplate
{
typedef typename extract_value_type<T>::value_type value_type;
};
Online demo : http://ideone.com/mbyvj
Now in C++11, you can use variadic template to make extract_value_type
work with class templates which take more than one template arguments, such as std::vector
, std::set
, std::list
etc.
template<template<typename, typename ...> class X, typename T, typename ...Args>
struct extract_value_type<X<T, Args...>> //specialization
{
typedef T value_type;
};
Demo : http://ideone.com/SDEgq