具有模板参数取决于参数列表

Having a template parameter depend on a parameter list

本文关键字:参数 取决于 列表      更新时间:2023-10-16

我已经定义了类

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;
};