查找模板类型为c++的模板类型

Find template type of a template type c++

本文关键字:类型 c++ 查找      更新时间:2023-10-16

我想有一个函数,可以采取许多不同的东西(为了简单),像这样:

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和构造函数。

如果T不是某个类模板,我希望type_to_return<T>::type只是T。否则,我希望它是该类的第一个模板参数。对于int,我要返回int,对于MultOp<float,int,double>,我要返回float

我该怎么做?我想我需要这样做:

// 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:

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<T, N>

请注意,stl容器声明了一些typedef来检索模板参数std::vector<T, Alloc>::value_type,即T