问题描述
我试图从类型 E = T
推导出底层模板类型 T
>。这将例如使得可以制作可以与若干相似类型的容器中的一个一起使用的模板函数pair_maker(const E& a)。粗糙元代码:
I'm trying to deduce the underlying template type T
from a type E = T<T2,T3>
. This would for example make it possible to make a template function pair_maker(const E & a) which can be used with one of several similar types of containers. Rough meta code:
template <typename T>
auto pairmaker(const E & a) -> PairContents<E,std::string>::type {
ContainerPairMaker<E,std::string>::type output;
... some code ...
return output;
}
PairContents< E,std :: string& / code>
PairContents<E,std::string>
会将向量< int>
转换为 ; pair(int,std :: string)>
或无论什么< T1>
std :: string)> 。
would transform the type vector<int>
into vector<pair(int,std::string)>
or whatever<T1>
into whatever<pair(T1,std::string)>
.
类型解析的另一个类似示例是std :: array以找出容器类型以创建新的类似数组。例如对于这些类型的函数(这是现在的实际工作代码)
Another similar example of type dissection is for std::array (or similar containers) where I like to figure out the container type to make a new similar array. For example for these kind of functions (this is actual working code now)
template <typename T >
auto make_some3(const T & a)
-> std::array<typename T::value_type,10*std::tuple_size<T>::value>{
return std::array<typename T::value_type,10*std::tuple_size<T>::value>{} ;
}
这个工作正常,但我后面是明确使用'std :: array'automatic。
This works fine but what I'm after is to make the explicit use of 'std::array' automatic.
对于std :: array,有tuple_size trait可以帮助,类似的东西可以用来找到类型
For std::array there's the tuple_size trait which helps, and a similar thing can be used to find the type
for any second argument, but again I can't think of anything for finding the container type.
总结:什么样的机器(如果有的话)可以使用对于这样的情况。在何种程度上可以处理模板参数,模板模板参数,任意数量的参数和未知类型的非模板参数的混合。
To summarize: what kind of machinery (if any) can be used for cases like these. To which extent is it possible to deal with mixes of template arguments, template-template arguments, any number of arguments, and non-template arguments of unknown types.
推荐答案
以下是一个想法:
template <typename T, typename ...>
struct tmpl_rebind
{
typedef T type;
};
template <template <typename ...> class Tmpl, typename ...T, typename ...Args>
struct tmpl_rebind<Tmpl<T...>, Args...>
{
typedef Tmpl<Args...> type;
};
用法:
typedef std::vector<int> IV;
typedef typename tmpl_rebind<IV, std::pair<double, std::string>>::type PV;
现在 PV = std :: vector< std :: pair& std :: string>>
。
这篇关于模板元编程:将指定模板分割为类型T <T2,T3 N,T4,...的性状(特征)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!