具有模板参数取决于参数列表
Having a template parameter depend on a parameter list
我已经定义了类
template <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
现在,我需要定义一个模板参数为某个参数包的模板类Foo
,并且为该参数包实例化了类型Bar::inner_type
的值。不幸的是,我似乎无法做到。如果我这样定义它:
template <Bar<Ts...>::inner_type SomeValue, typename... Ts> struct Foo { };
使用时,编译器尚未看到参数包,因此无法识别Ts
。但是,如果我这样定义它:
template <typename... Ts, Bar<Ts...>::inner_type SomeValue> struct Foo { };
在我尝试在其他模板参数之前使用参数包的编译器嘲笑。
那么我该怎么做?
注意:如果重要的话,这对我而言,GCC 4.9.3。
您可以部分专业化结构:
template<typename...>
struct Bar { using inner_type = int; };
template <typename T, typename T::inner_type T>
struct Foo;
template <typename... Ts, typename Bar<Ts...>::inner_type SomeValue>
struct Foo<Bar<Ts...>, SomeValue> { };
int main() {
Foo<Bar<int>, 3> foo;
}
这样推导了Ts
参数包,并且Foo
期望第二个模板参数为类型Bar<Ts...>::inner_type
。
我能想到的最好的事情:
template <class Inner, Inner Val, class... Args>
struct Foo {
static_assert(std::is_same<Inner, typename Bar<Args...>::inner_type>::value, "Wrong type");
};
您需要明确命名类型。
这是否解决了问题?
#include <type_traits>
using namespace std;
template <typename... Ts> class Bar {
public:
using inner_type = int;
};
template <typename... Ts> class Foo {
using bar_inner_type = typename Bar<Ts...>::inner_type;
static_assert(is_same<int, bar_inner_type>::value,"");
};
如果我正确理解了您的问题,则可以做这样的事情:
template <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
template <typename... Ts> struct Foo {
using inner_type = typename Bar<Ts...>::inner_type;
};
相关文章:
- 将强制转换简化为取决于参数的类型
- cpp 模板专用化,错误说参数 1 的类型为 T,这取决于参数 T
- 模板函数,其中模板参数类型取决于函数参数
- GCC:指定的界限取决于源参数的长度
- 具有尾随返回类型的通用 lambda,具体取决于 C++11 中的可变参数
- 类模板中的std ::数组的大小,具体取决于模板参数
- LIBELAS是否取决于相机参数
- 具有取决于模板参数的方法的模板类
- 模板层次结构中的可选虚拟函数,具体取决于参数
- 约束模板参数取决于传递的函子
- 为什么固定尺寸错误发生取决于默认参数
- C++14 lambda 的默认参数类型推导,具体取决于前面的参数
- 委托构造函数和默认参数,具体取决于其他参数
- 取决于参数的数量,将其返回结构对象,并将其分配给常规结构的对象
- 具有模板参数取决于参数列表
- 返回类型取决于模板参数
- 是否可以定义一个 C++11 可变参数类模板,其可变参数基数取决于整数模板参数
- 返回取决于sizeof的变量类型..参数包
- 模板化结构的友元函数,其参数类型取决于结构的内部
- 变量模板函数,其中返回类型取决于模板参数列表