【发布时间】:2014-12-03 03:23:44
【问题描述】:
尝试从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 中。
【问题讨论】:
-
std中的大多数类型都不是为了继承而设计的,包括std::function。 -
@Yakk 感谢您的提醒,尽管“你应该永远”的想法在"Thou shalt not inherit from std::vector" 辩论中有点争议。不过,目前这只是一个本地实验。
-
您不妨私下进行,只需使用声明来执行您想要执行的操作。这样就没有机会从基类中获得支持。
标签: c++ inheritance c++11 constructor using