c++ - 函数式模板语法

标签 c++ templates c++14 variadic

我正在尝试编写一个相当简单的类,它接受一个函数和一些参数,并且可以稍后使用参数执行该函数。

目前,这是我的代码:

template<typename R, typename... Args>
class Delayed
{
public:
    using FunctionT = std::function<R(Args...)>;

    Delayed(FunctionT func, Args... args) : func(func), args(std::forward<Args>(args)...)
    {

    }

private:
    FunctionT func;
    std::tuple<Args...> args;
};

int main()
{
    std::function<double(double)> doubleMe = [](double x) { return x * 2.0; };

    //Works
    Delayed<double, double> delayed1(doubleMe, 2.0);

    //Doesn't work
    Delayed<double(double)> delayed2(doubleMe, 2.0);
}

问题是当我通过double(double)时作为参数,而不是 RdoubleArgsdouble ,它通过 double(double)R没什么可做的Args .

According to cppreferencestd::function 的模板参数是 template< class R, class... Args > 。所以如果我给它A(B,C) ,它将通过A对于参数 RB,C对于可变参数 Args 。但是当我将其传递给我的类(class)时,它会传递 A(B,C)对于 R并且不为可变参数 Args 传递任何内容.

这个函数语法应该如何使用以及为什么它适用于 std::function但不是我的类(class)?

最佳答案

So if I give it A(B,C), it will pass A for the argument R and B,C for the variadic argument Args.

是的,但原因不是你想象的那样。如果仔细观察,您会发现 std::function 部分专门用于任何函数类型:

template<typename R, typename... Args>
class function<R(Args...)>;
//            ^^^^^^^^^^^^

您可以将其想象为非常原始的模式匹配。如果您使用 int(int, double) 实例化 function,则 Rint 是有意义的,并且Argsint, double。如果(部分)特化比包罗万象的通用主模板更好匹配,那么它就会被选择,这就是这里发生的情况。

记住:double(double) 是一种类型,它是一个函数。没有任何涉及它的特殊规则。因此,对于您的情况,您将这样做:

template<typename R, typename... Args>
class Delayed<R(Args...)> : public Delayed<R, Args...> {
  //         ^^^^^^^^^^^^
  //       partially specialize to decompose function types

  // We need to inherit constructors (only).
  using Delayed<R, Args...>::Delayed;
};

希望它能消除困惑。

关于c++ - 函数式模板语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550541/

相关文章:

c++ - 替换冗余子集

c++ - CMake 为 FIND_PACKAGE 设置起始路径?

c++ - 重用 auto 类型的变量

c++ - vector 中允许的事件迭代器的数量

c++ - 使用模板将std::shared_ptr <Derived>上载到std::shared_ptr <Base>

c++ - "function type"表示什么

c++ - ˋtypedefˋ 中的异常规范是完全禁止的还是仅在顶层?

c++ - 从进程导航到它的父进程

javascript - 从 Joomla 模板 (YooTheme) 中删除日期

python - 在 C++14 中使用泛型 lambda 和自动返回类型特性获得的不同结果