简体   繁体   English

查找模板类型C ++的模板类型

[英]Find template type of a template type c++

I would like to have a function that can take many different things (for simplicity) like so: 我希望有一个可以接受许多不同功能(为简单起见)的函数,如下所示:

template <typename T>
typename type_to_return<T>::type   // <-- Use type_to_return to get result type
foo(T t)
{
    return typename type_to_return<T>::type(T); // <-- Build a thing!
}

I would then specialize the type_to_return class for the types I have created. 然后,我将专门针对我创建的类型使用type_to_return类。 This would make the entry be one function and I could then just define new type_to_return s and constructors. 这将使该条目成为一个函数,然后我就可以定义新的type_to_return和构造函数。

I want type_to_return<T>::type to be just T if T is not some class template. 如果T不是某些类模板,我希望type_to_return<T>::type只是T Otherwise I want it to be that class's first template parameter. 否则,我希望它成为该类的第一个模板参数。 So for int , I get back int , and for MultOp<float,int,double> , I want to get back float . 因此对于int ,我返回int ,对于MultOp<float,int,double> ,我想返回float

How do I do that? 我怎么做? I think I need to do something like: 我想我需要做些类似的事情:

// Base version
template <typename T>
struct type_to_return
{
    typedef T type;
};

// Specialized type
template <template <typename> class T>
struct type_to_return<T <any_type_somehow> >
{
    typedef template boost::magic_type_unwrapper<T>::param<1>::type type;
};

You may implement a type_unwrapper as follow: 您可以如下实现type_unwrapper

template <typename T>
struct type_unwrapper;

template <template <typename...> class C, typename... Ts>
struct type_unwrapper<C<Ts...>>
{
    static constexpr std::size_t type_count = sizeof...(Ts);

    template <std::size_t N>
    using param_t = typename std::tuple_element<N, std::tuple<Ts...>>::type;
};

which works as long there is no template value as in std::array<T, N> . 只要没有std::array<T, N>模板值, std::array<T, N>

Note also that stl container declare some typedef to retrieve there template arguments as std::vector<T, Alloc>::value_type which is T . 还要注意,stl容器声明一些typedef来检索模板参数,如std::vector<T, Alloc>::value_type ,即T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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