2014-12-03 59 views
0

试图从std::function中派生一个类,并为初学者继承构造函数。这是我的猜测:从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。

+0

大多数类型'std'没有被设计成与继承,包括'的std :: function'。 – Yakk 2014-12-03 03:36:33

+0

@Yakk感谢您的提醒,虽然“你应该永远”的想法是有点争议的[“你不应该继承自std :: vector”](http://stackoverflow.com/questions/ 4353203/thou-shalt-not-inherit-from-stdvector)辩论。然而,这仅仅是一个当地的实验。 – HostileFork 2014-12-03 03:40:36

+0

你也可以私下做,并且使用声明来实现你想要做的事情。这不会让基层得不到支持。 – chris 2014-12-03 05:25:54

回答

1

要添加到克里斯的answer,如果你希望你当前的定义工作,使用

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

如果你想与std::function相同的漂亮MyFunction<R(Args...)>语法,那么您必须提供未实现的主类模板以及从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

2
MyFunction<void()> mine 

根据你的类,由此推断Rvoid()Args...作为空参数组。如果你想要一个语法工作,你必须专注你的类模板:

template<class R, class... Args> 
class MyFunction<R(Args...)> : blah 
+0

啊,我明白了。所以这就是为什么在非专用的['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)上有'/ * undefined * /'...谢谢! – HostileFork 2014-12-03 03:45:46