c++ - 在 C++ 中将内部模板类作为模板参数传递

标签 c++ templates

我正在尝试将(常规类的)内部模板类传递给另一个接受模板作为参数的类。

接受模板的类是:

template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};

所以当我有类似 using List = TypeList<int, float, double>; 的东西时我可以
static_assert(std::is_same<List::template Apply<std::tuple>,
                           std::tuple<int, float, double>>::value);

但如果我改变 std::tuple所以一个内部模板类,它停止工作。 IE。,
struct Outer {
  template <typename... P> struct Inner {};
};

static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);

不起作用。

我的编译器提示

error: invalid use of template-name ‘Outer::Inner’ without an argument list



如果我用template <typename... P> using Flat = Outer::Inner<P...>;“展平”内部模板类,它会起作用。 .

我的问题是,有没有办法让内部模板类工作,而不用别名和展平它?我错过了typenametemplate某处的关键字?

完整的例子是:
#include <tuple>
#include <type_traits>

template <typename... T> struct TypeList {
  template <template <typename...> typename P> using Apply = P<T...>;
};

struct Outer {
  template <typename... P> struct Inner {};
};

template <typename... P> using Flat = Outer::Inner<P...>;

int main() {
  using List = TypeList<int, float, double>;
  static_assert(std::is_same<List::template Apply<std::tuple>,
                             std::tuple<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<Flat>,
                             Outer::Inner<int, float, double>>::value);
  static_assert(std::is_same<List::template Apply<typename Outer::Inner>,
                             Outer::Inner<int, float, double>>::value);
}

最佳答案

typename Outer::Inner错误为 Inner不是类型而是模板。

您甚至可以在此处删除所有类型名/模板,因为没有依赖类型问题。

static_assert(std::is_same<List::Apply<Outer::Inner>,
                           Outer::Inner<int, float, double>>::value);

在从属上下文中,它将是
// template <typename OuterT> /*..*/
static_assert(std::is_same<List::Apply<OuterT::template Inner>,
                           typename OuterT::template Inner<int, float, double>>::value);

Demo

关于c++ - 在 C++ 中将内部模板类作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291982/

相关文章:

c++ - 有效地从 unordered_set 中删除 unique_ptr

c++ - 标题保护 C++ 的“类”类型重新定义错误

c++ - 为什么我的专用模板函数 'OverloadedFunk' 在 C++ 中给出 "could not be resolved"错误?

c++ - "explicit template argument list not allowed"使用 g++,但使用 clang++ 编译?

c++ - 使用初始值设定项列表将模板大小的数组传递给函数

C++:为该结构之外的结构编写函数?

c# - 如何在 C# 上为包装的 C++ 方法编写签名,该方法具有指向函数及其参数的指针?

c++ - 接受无限相同数量的 3 种类型的函数

C++ 模板和工厂

c++ - 科学模拟中适当的类(class)成员访问