我正在编写一个简单的 C++ HTTP 服务器框架。在我的Server
课堂上,我可以添加Route
's. 每个路由都包含一个路径、一个 HTTP 方法和一个Controller
(这是在发出请求时要调用的函数管道。)Controller
该类是通过接收std::function
's 列表(或者更准确地说:)来构造的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\" }]";
},
}
);
在这种情况下,我想让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
我想知道的是:为什么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&);
};
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);
}
}