c++staticc++17structured-bindings

Using `static` keyword with Structured Binding


I'm trying to use C++17 structured binding to return a pair of values and I want those values to be both static and const so that they are computed the first time the function they're in is called and then they maintain their uneditable values for the lifetime of the program. However when I do this I get the error: a structured binding cannot declare an explicit storage class error and I'm not sure why or how to fix it. A minimum working example is below.

#include <iostream>
#include <utility>

static const std::pair<double, double> pairReturn()
{
    return {3,4};
}

int main()
{
    static const auto [a, b] = pairReturn();

    std::cout << a << std::endl;
    std::cout << b << std::endl;

    return 0;
}

Solution

  • The error is a bit confusing, but structured binding to static variables is just not supported with c++17. Either use a different solution, or c++2a. A different solution could just be an additional line:

    static std::pair pr = pairReturn();
    auto &[a, b] = pr;