c++ - 从 std::function 继承构造函数时为 "function returning a function"

标签 c++ inheritance c++11 constructor using

尝试从 std::function 派生一个类,对于初学者来说,继承构造函数。这是我的猜测:

#include <iostream>
#include <functional>
using namespace std;

template< class R, class... Args >
class MyFunction : public std::function<R(Args...)> {
public:
    using std::function<R(Args...)>::function;
};

int main() {
    std::function<void()> f_display_42 = []() { std::cout << 42; }; //works

    MyFunction<void()> mine = []() { std::cout << 42; }; //errors
}

返回的错误是:

prog.cpp: In instantiation of ‘class MyFunction<void()>’:
prog.cpp:14:24:   required from here
prog.cpp:6:7: error: function returning a function
 class MyFunction : public std::function<R(Args...)> {
       ^
prog.cpp:8:38: error: function returning a function
     using std::function<R(Args...)>::function;
                                      ^
prog.cpp:8:38: error: using-declaration for non-member at class scope
prog.cpp: In function ‘int main()’:
prog.cpp:14:55: error: conversion from ‘main()::__lambda1’
     to non-scalar type ‘MyFunction<void()>’ requested
     MyFunction<void()> mine = []() { std::cout << 42; };

在 GCC 4.8.2 中。

最佳答案

添加到克里斯的 answer ,如果您希望当前的定义有效,请使用

MyFunction<void> mine = []() { std::cout << 42; };

如果你想要同样漂亮的 MyFunction<R(Args...)>语法为 std::function ,那么您必须提供一个未实现的主类模板,以及一个派生自 std::function 的特化。 (这正是 std::function 所做的)。

template< class R, class... Args >
class MyFunction;

template< class R, class... Args >
class MyFunction<R(Args...)> : public std::function<R(Args...)>
{ ... }

Live demo

关于c++ - 从 std::function 继承构造函数时为 "function returning a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263092/

相关文章:

c++ - type 不提供调用操作符

c++ - 如何将 Blitz++ 子数组作为过程的输入/输出参数传递

c++ - 交换可整除的数字并获得声明为无效的错误

java - Java中如何拥有动态数据类型的变量?

c++ - 在 C++ 中处理非 Ascii 字符

c++ - 在 Boost.Asio Stackful Coroutine 中产生

c++ - SetWindowsHookEx(WH_KEYBOARD) 不使用线程 ID

c++ - 字符串和 unordered_map 运行缓慢

java - 当我无法使用基类引用调用派生类方法时,动态多态性有何用处

c# - 在 Entity Framework Code First 中忽略基类型是否也会忽略子类?