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

标签 c++ c++17 constexpr type-erasure std-function

我有一个类似于 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/

相关文章:

c++ - OpenMP parallel-for 效率查询

c++ - 模板函数无法识别由 auto 变量引用的 lambda

c++ - 为什么我无法检索变体的索引并使用它来获取其内容?

c++ - 在 constexpr 函数中返回一个 C 字符串 : why no warning from the compiler?

c++ - 构造函数的 Constexpr 条件

c++ - 在 C++17 中修改 constexpr 函数中的全局变量

c++ - Net-SNMP - 在新的 MIB 模块中编译,而不编译整个 SNMP 代理

c++ - QAxObject 没有为 COM 对象创建槽信号

android - 在android NDK jni中加密和解密utf8字符串

c++ - 模板化参数中仿函数的默认参数