c++ - 使用来自另一个模板的参数对模板进行柯里化(Currying)

标签 c++ templates metaprogramming currying

我有类 Foo,它有两个模板参数,AB:

template<typename A, typename B>
struct Foo {};

我还有类 Base,它有一个模板模板参数:

template<template<typename B> typename Foo>
struct Base {};

我想编写类 Derived 假设如下:

  • Derived 有一个模板参数 (A)
  • Derived extends class Base
  • Derived 作为模板参数传递给类 BaseFoo,但带有一个参数“currying”(A)

我该怎么做?


这是我的(not working)解决方案:

template<template<typename B> typename Foo>
struct Base {};

template<typename A, typename B>
struct Foo {};

template<template<typename A, typename B> typename Foo, typename A>
struct BindFirst {
    template<typename B>
    using Result = Foo<A, B>;
};

template<typename A>
struct Derived : Base<

        // error is here
        typename BindFirst<Foo, A>::Result

> {};

这给我错误:

template argument for template template parameter must be a class template or type alias template

最佳答案

模板 Base 需要一个模板作为第一个参数,但您试图传递一个依赖类型(由 typename 指示),因此出现错误消息。此外,BindFirst 中的嵌套别名 Result 是一个模板,因此需要一个模板参数才能与 typename 一起使用。所以不是

typename BindFirst<Foo, A>::Result

你必须告诉编译器 Result 实际上是一个模板,使用

BindFirst<Foo, A>::template Result

Live example

关于c++ - 使用来自另一个模板的参数对模板进行柯里化(Currying),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53270817/

相关文章:

c++ - 冒泡排序崩溃程序 C++

c++如何创建派生类模板的实例

c++ - 模板中的函数类型无法编译

c++ - 使用模板函数的不同类型的输入

c++ - 通用回调

java - Kotlin 反射与 Java 的互操作性

c++ - 在 dlib 窗口中打印文本

c++ - Boost.Interprocess 是否牺牲性能来实现可移植性

c++ - 检测已知中心的部分隐藏椭圆的边界(OpenCV)

c++ - 在另一个 std::tuple 中创建类型为 "contained"的 std::tuple