首页 > 解决方案 > 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;
    }
};

我无法编译代码。我不明白这是怎么回事?

标签: c++jsonoopstl

解决方案


让我们考虑以下示例:

constexpr auto f = []() {};

int main()
{
    f();
    return 0;
}

这里,constexpr变量的类型fconst<lambda()>。编译器抱怨<lambda()>不是文字,因为它是一个闭包类型,而闭包类型只是从 C++17 开始的文字。

现在,你可以用 C++17 试试这个,看看你是否可以libcurl在编译时使用,但我会认为这超出了范围。请记住,说明constexpr符声明可以在编译时评估函数或变量的值(ref)。因此,如果您在 lambda 中使用无法在编译时评估的变量或函数,则该 lambda 也无法在编译时评估,因此不能是constexpr.


推荐阅读