gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:21:29 36 4
gpt4 key购买 nike

尝试从 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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com