簡體   English   中英

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

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

我希望有一個可以接受許多不同功能(為簡單起見)的函數,如下所示:

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>模板值, std::array<T, N>

還要注意,stl容器聲明一些typedef來檢索模板參數,如std::vector<T, Alloc>::value_type ,即T

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM