具有模板参数取决于参数列表
Having a template parameter depend on a parameter list
我定义了class
template <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
现在,我需要定义一个模板化的 class 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 对我来说失败了。
这是否解决了问题?
#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 <class Inner, Inner Val, class... Args>
struct Foo {
static_assert(std::is_same<Inner, typename Bar<Args...>::inner_type>::value, "Wrong type");
};
您需要明确命名类型。
您可以部分特化您的结构:
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 <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
template <typename... Ts> struct Foo {
using inner_type = typename Bar<Ts...>::inner_type;
};
我定义了class
template <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
现在,我需要定义一个模板化的 class 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 对我来说失败了。
这是否解决了问题?
#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 <class Inner, Inner Val, class... Args>
struct Foo {
static_assert(std::is_same<Inner, typename Bar<Args...>::inner_type>::value, "Wrong type");
};
您需要明确命名类型。
您可以部分特化您的结构:
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 <typename... Ts> struct Bar {
using inner_type = /* whatever */;
};
template <typename... Ts> struct Foo {
using inner_type = typename Bar<Ts...>::inner_type;
};