获取模板类型的模板参数类型
Getting at template parameter types of a template type
我有一个关于模板的问题,它在代码中:
template<typename T>
struct foo {
T t;
};
template<typename FooType>
struct bar {
T t; //<- how to get T here (preferably without using typedef in foo)
};
这是一个通用的模板参数类型提取器:
#include <tuple>
template <typename> struct tuplify;
template <template <typename...> class Tpl, typename ...Args>
struct tuplify<Tpl<Args...>>
{
using type = std::tuple<Args...>;
};
template <typename T, unsigned int N>
using get_template_argument
= typename std::tuple_element<N, typename tuplify<T>::type>::type;
用法:
get_template_argument<std::vector<int>, 1> a; // is a std::allocator<int>
或者在你的情况下:
get_template_argument<FooType, 0> t;
如果我正确理解了你的问题,你可以像下面这样使用模板专门化。给定foo<>
类模板:
template<typename T>
struct foo {
T t;
};
定义bar<>
主模板和相应的专门化:
template<typename FooType>
struct bar;
template<typename T>
struct bar<foo<T>> {
T t; // T will be int if the template argument is foo<int>
};
假设您总是应该通过提供foo<>
的实例作为类型参数来实例化bar
,您可以不定义主模板。
专门化将匹配foo<T>
模式,从而给出在T
中实例化foo<>
的类型。
#include <type_traits>
int main()
{
bar<foo<int>> b;
// This will not fire, proving T was correctly deduced to be int
static_assert(std::is_same<decltype(b.t), int>::value, "!");
}
下面是相应的实例
如果您不想或不能为foo
添加typedef,您可以另外编写一个独立的"extractor"模板
template <typename T> struct ExtractT;
template <typename T> struct ExtractT<foo<T> > {
typedef T type;
};
作为
template<typename FooType>
struct bar {
typename ExtractT<FooType>::type t;
};
你可以进一步将ExtractT
与foo
解耦
template <typename T> struct ExtractT;
template <template <typename> class C, typename T> struct ExtractT<C<T> > {
typedef T type;
};
等等,直到您从Boost或c++ 11标准库中重新发明一些东西:)顺便说一句,这感觉应该已经以更通用的解决方案的形式可用....
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法