如何获取最里面的模板参数类型? [英] How can I get the innermost template parameter type?
问题描述
在一个类的虚拟示例中
typedef myStruct<myStruct<myStruct<int>>> mv;
int
是最里面的模板参数。 如何获取任意嵌套深度的参数类型?
int
is the innermost template parameter. How can I get the type of that parameter for arbitrary nesting depth?
获取最内层类型的机制
innermost<mv>::type -> int
愿望清单
WishList
-
可以使用模板别名来完成此操作吗(模板模板参数是此处缺少的功能)?
Can this be done using template aliases (template template parameters are a missing feature here)?
在示例中,我的类型是
vector<vector<vector<int>>>
给定 vector,有没有一种方法可以执行相同的操作
需要一个额外的模板参数?当然,可以采用不同的实现方式,但是有没有办法扩展第一个问题的解决方案以解决这些情况?
Is there a way to perform the same operation, given that vector
expects an extra template parameter ? Ofcourse a distinct implementation could be divised but is there a way to scale the solution for the first problem to handle these cases as well ?
推荐答案
尝试以下操作。如果模板具有多个元素,它还会返回一个元组:
Try the following. It also returns a tuple if the template has more than one element:
#include <tuple>
#include <type_traits>
template<typename T>
struct innermost_impl
{
using type = T;
};
template<template<typename> class E, typename T>
struct innermost_impl<E<T>>
{
using type = typename innermost_impl<T>::type;
};
template<template<typename...> class E, typename... Ts>
struct innermost_impl<E<Ts...>>
{
using type = std::tuple<typename innermost_impl<Ts>::type...>;
};
template<typename T>
using innermost = typename innermost_impl<T>::type;
template<class>
struct X;
static_assert(std::is_same<innermost<X<X<X<int>>>>, int>::value, "");
int main()
{
}
这篇关于如何获取最里面的模板参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!