查找模板类型 c++ 的模板类型 [英] Find template type of a template type c++

查看:41
本文介绍了查找模板类型 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!
}

然后我会为我创建的类型专门化 type_to_return 类.这将使条目成为一个函数,然后我可以定义新的 type_to_return 和构造函数.

I would then specialize the type_to_return class for the types I have created. This would make the entry be one function and I could then just define new type_to_returns and constructors.

如果 T 不是某个类模板,我希望 type_to_return::type 只是 T.否则我希望它成为该类的第一个模板参数.所以对于int,我要返回int,对于MultOp,我想返回float.

I want type_to_return<T>::type to be just T if T is not some class template. 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.

我该怎么做?我想我需要做一些类似的事情:

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

推荐答案

你可以实现一个 type_unwrapper 如下:

You may implement a type_unwrapper as follow:

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

只要没有 std::array 中的模板值,它就可以工作.

which works as long there is no template value as in std::array<T, N>.

还要注意,stl 容器声明了一些 typedef 以将模板参数检索为 std::vector::value_typeT.

Note also that stl container declare some typedef to retrieve there template arguments as std::vector<T, Alloc>::value_type which is T.

这篇关于查找模板类型 c++ 的模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆