c++ - Consexpr 变量不能具有非文字类型“const CurlHandle”
问题描述
在以下代码中,我在constexpr static auto f = [](CURL* c)
类的私有部分的行中收到错误和警告。
Constexpr 变量不能有非文字类型 'const CurlHandle::(lambda at /alienware/CLionProjects/Bitcoin/main.cpp:48:31)' lambda 闭包类型在 C++17 之前是非文字类型
class CurlHandle {
private :
CURL_ptr curlptr;
std::string data;
std::array<char, CURL_ERROR_SIZE> errorBuffer;
constexpr static auto f = [](CURL* c) {
curl_easy_cleanup(c);
curl_global_cleanup();
};
public :
CurlHandle() : curlptr(curl_easy_init(), f) {
CURLcode code = CURLE_OK;
code = curl_global_init(CURL_GLOBAL_ALL);
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), "Unable to global init");
}
curl_easy_setopt(curlptr.get(), CURLOPT_ERRORBUFFER, &errorBuffer[0]);
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), "Unable to set error buffer");
}
curl_easy_setopt(curlptr.get(), CURLOPT_WRITEFUNCTION, dataHandler);
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), std::string(&errorBuffer[0]));
}
curl_easy_setopt(curlptr.get(), CURLOPT_WRITEDATA, &data);
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), std::string(&errorBuffer[0]));
}
}
void setUrl(const std::string& url) {
CURLcode code = curl_easy_setopt(curlptr.get(), CURLOPT_URL, url.c_str());
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), std::string(&errorBuffer[0]));
}
}
void fetch() {
data.empty();
CURLcode code = curl_easy_perform(curlptr.get());
if (code != CURLE_OK){
throw CurlException(static_cast<int>(code), std::string(&errorBuffer[0]));
}
}
const std::string& getFetchedData() const {
return data;
}
};
我无法编译代码。我不明白这是怎么回事?
解决方案
让我们考虑以下示例:
constexpr auto f = []() {};
int main()
{
f();
return 0;
}
这里,constexpr
变量的类型f
是const<lambda()>
。编译器抱怨<lambda()>
不是文字,因为它是一个闭包类型,而闭包类型只是从 C++17 开始的文字。
现在,你可以用 C++17 试试这个,看看你是否可以libcurl
在编译时使用,但我会认为这超出了范围。请记住,说明constexpr
符声明可以在编译时评估函数或变量的值(ref)。因此,如果您在 lambda 中使用无法在编译时评估的变量或函数,则该 lambda 也无法在编译时评估,因此不能是constexpr
.
推荐阅读
- gzip - 如何在 C 中直接读取 .gz 文本文件
- python - 为什么 selenium 只拾取前 12 项?
- react-native - 每次单击按钮时如何更改内容?
- passport.js - 在 NestJS 中更新用户名后如何刷新 JWT 令牌?
- uikit - 在 SwiftUI 中,如何将视频循环添加为全屏背景图像?
- android - 没有在 android 上的 pjsip 呼叫上获得音频
- javascript - 如何获取屏幕宽度,并从 JS 传递到 PHP?
- c++ - 嵌入式设备 -> std::thread -> FreeRTOS?
- angular - Angular 8 路由:更改 URL 无法导航到预期页面
- javascript - 在等待 API 调用返回数据时 React 实现活动轮