gpt4 book ai didi

c++ - Constexpr 可构造函数对象

转载 作者:行者123 更新时间:2023-12-02 09:26:37 25 4
gpt4 key购买 nike

我有一个类似于 this one 的问题,但对于更有限的情况,我认为应该以某种方式可能:我想从多个 lambda 构造一个静态 constexpr 函数调用数组,每个 lambda 共享相同的签名。 static 和 constexpr 部分在这里很重要,因为我在嵌入式系统上,我想确保此类表最终出现在 Flash 中。

所以基本上我想做的是

#include<vector>
#include<functional>
#include<variant>

using params_t = std::vector<std::variant<int, float /*maybe others*/ >>;

struct command_t {
using callable_t = std::function<void(params_t)>;

const callable_t func;
//other members..
};

class AClass {
template<typename func_t>
constexpr static command_t::callable_t make_callable(func_t fun) {
return [fun](params_t params){/*construct a call to fun using params and template magic*/};
}

static void mycommand();
static void mycommand2(int i);

//The following fails:
///"error: in-class initialization of static data member 'const command_t AClass::commands [2]' of non-literal type"
static constexpr command_t commands[2] = {command_t{make_callable(mycommand)},
command_t{make_callable(mycommand2)}};
};

On coliru

请注意,这里的类型删除非常有限,因为 lambda 的签名仅因 fun 捕获的签名而变化。函数调用显然不需要(也不可能)是 constexpr,只需构造即可。

所以基本上我的问题是我可以以某种方式使 commands 数组 static constexpr ,或者以某种方式使用 std::function, 或类似的东西inplace_function ,或者在这种特定情况下通过旋转我自己的代码来类型删除 lambda?

最佳答案

一般来说,这是不可能的,因为 lambda 的捕获可以变得任意大,因此,在某些时候我们需要一个堆分配,这会扼杀 constexpr pre-C++20 的任何希望(而且我不这样做)我认为 C++20 对于这种情况也有很大帮助)。

但是如果我认为正确并且我们可以做到的话,您只想捕获函数指针:

#include <vector>
#include<variant>

using params_t = std::vector<std::variant<int, float /*maybe others*/ >>;

struct command_t {
using callable_t = void (*)(std::vector<params_t>);

const callable_t func;
//other members..
};

template<auto f>
void wrap(std::vector<params_t>){
// make this dependent of f, maybe use function_traits for fancy stuff
}
class AClass {

static void mycommand();
static void mycommand2(int i);

static constexpr command_t commands[2] = {wrap<mycommand>, wrap<mycommand2>};
};

int main() {

}

感谢xskxzr提出的宝贵建议。

关于c++ - Constexpr 可构造函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60546332/

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