constexpr 构造函数的参数类型 'std::function' 不是文字类型

And*_*ton 5 c++ lambda constexpr c++11 constexpr-function

我正在编写一个简单的 C++ HTTP 服务器框架。在我的Server课堂上,我可以添加Route's。每个路由都包含一个路径、一个 HTTP 方法和一个Controller(这是发出请求时要调用的函数的管道。)该类Controller是通过接收 的列表std::function(或者更准确地说std::function<void(const HTTPRequest&, HTTPResponse&, Context&)>:)来构造的,但大多数有时(或者我应该说每次),这Controller将使用 lambda 函数文本列表进行初始化,如以下代码所示:

server.add_route("/", HTTPMethod::GET,
                {
                    [](auto, auto& response, auto&) {
                        const int ok  = 200;
                        response.set_status(ok);
                        response << "[{ \"test1\": \"1\" },";
                        response["Content-Type"] = "text/json; charset=utf-8";
                    },
                    [](auto, auto& response, auto&) {
                        response << "{ \"test2\": \"2\" }]";
                    },
                }
        );
Run Code Online (Sandbox Code Playgroud)

既然如此,我想将add_route函数设为 a constexpr,因为如果我错了,请纠正我,constexpr函数可以在编译时执行。

所以,当我做一切的时候constexpr,我发现了以下错误:

Controller.cpp:9:1 constexpr constructor's 1st parameter type 'Callable' (aka 'function<void (const HTTPRequest &, HTTPResponse &, Context &)>') is not a literal type
Run Code Online (Sandbox Code Playgroud)

我想知道的是:为什么std::function's 不能是文字类型?有什么办法可以绕过这个限制吗?

下面是类的代码Controller。我知道仍然存在其他编译错误,但这是我现在正在解决的主要问题。提前致谢!

controller.hpp

#pragma once

#include <functional>
#include <initializer_list>
#include <vector>

#include "context.hpp"
#include "httprequest.hpp"
#include "httpresponse.hpp"

typedef std::function<void(const HTTPRequest&, HTTPResponse&, Context&)> Callable;
template <size_t N>
class Controller {
private:
    std::array<Callable, N> callables;

public:
    static auto empty_controller() -> Controller<1>;

    constexpr explicit Controller(Callable);
    constexpr Controller();
    constexpr Controller(std::initializer_list<Callable>);

    void call(const HTTPRequest&, HTTPResponse&, Context&);
};
Run Code Online (Sandbox Code Playgroud)

controller.cpp

#include "controller.hpp"

template <size_t N>
auto Controller<N>::empty_controller() -> Controller<1> {
    return Controller<1>([](auto, auto, auto) {});
}

template <>
constexpr Controller<1>::Controller(Callable _callable) :
    callables(std::array<Callable, 1> { std::move(_callable) }) { }

template <>
constexpr Controller<1>::Controller() :
    Controller(empty_controller()) { }


template <size_t N>
constexpr Controller<N>::Controller(std::initializer_list<Callable> _list_callables) :
    callables(_list_callables) { }

template <size_t N>
void Controller<N>::call(const HTTPRequest& req, HTTPResponse& res, Context& ctx) {
    for (auto& callable : callables) {
        callable(req, res, ctx);
    }
}
Run Code Online (Sandbox Code Playgroud)

Qui*_*mby 5

为什么 std::function 不能是文字类型?有什么办法可以绕过这个限制吗?

因为它使用类型擦除来接受任何可调用的。这需要多态性,直到 C++20 允许constexpr virtual. 您可以使用模板并直接捕获可调用对象,但其类型会蔓延Controller并进一步传播。

既然如此,我想将 add_route 函数设为 constexpr,因为如果我错了,请纠正我,constexpr 函数可以在编译时执行。

是的,如果给定 constexpr参数,该函数将在编译时执行。看它就像高级的常量折叠。此外,constexpr编译时上下文中使用的方法要么无法访问*this,要么也必须是 constexpr。特别是,constexpr方法只能constexpr在编译时更改实例的状态。否则该函数通常在运行时运行。

最后一点与您相关,在编译时运行 HTTP 服务器几乎没有意义,因此constexpr可能不需要并且不会有任何帮助。

编辑constexpr行为示例

struct Foo{
    //If all members are trivial enough and initialized, the constructor is constexpr by default.
    int state=10;
    //constexpr Foo()=default;
constexpr int bar(bool use_state){
    if(use_state)
        return state++;
    else
        return 0;// Literal
}
constexpr int get_state()const{
    return state;
}
};

template<int arg>
void baz(){}
int main(int argc, char* argv[])
{
   Foo foo;
   //Carefull, this also implies const and ::bar() is non-const.
   constexpr Foo c_foo;

   foo.bar(true);//Run-time, `this` is not constexpr even though `true` is
   foo.bar(false);//Compile-time, `this` was not needed, `false` is constexpr

   bool* b = new bool{false};
   foo.bar(*b);//Always run-time since `*b` is not constexpr



   //Force compile-time evaluation in compile-time context
   //Foo has constexpr constructor, creates non-const (temporary) constexpr instance
   baz<Foo().bar(true)>();
   baz<Foo().bar(false)>();
   baz<foo.bar(false)>();
   //ERROR, foo is not constexpr
   //baz<foo.bar(true)>();
   //ERROR, c_foo is const
   //baz<c_foo.bar(false)>();
   //Okay, c_foo is constexpr
   baz<c_foo.get_state()>();
   //ERROR, foo is not constexpr
   //baz<foo.get_state()>();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)