mardi 12 avril 2022

static constexpr chrono as struct member

I have an interface header with a struct like looks like this (C++11):

// header
struct MyStruct
{
    std::chrono::milliseconds time_1{defaultTime};
    std::chrono::milliseconds time_2{defaultTime};
    std::chrono::milliseconds time_3{defaultTime};

    // default value
    static constexpr std::chrono::milliseconds defaultTime{5000};
};

// cpp
constexpr std::chrono::milliseconds MyStruct::defaultTime;

int main()
{
    MyStruct ms{};
}

Everything is fine with GCC and MSVC, the problem is that on Clang 9 I get this error: Undefined symbols for architecture x86_64: "MyStruct::defaultTime":

I want to avoid code duplication and to keep that defaultTime{5000} visible to my library users in the header. But it should compile on Clang 9 also.

An alternative would be this, although I don't really like to default to be the first member there:

// header
struct MyStruct
{
    // default value
    const std::chrono::milliseconds defaultTime{5000};

    std::chrono::milliseconds time_1{defaultTime};
    std::chrono::milliseconds time_2{defaultTime};
    std::chrono::milliseconds time_3{defaultTime};
}

Any alternatives? thanks

Aucun commentaire:

Enregistrer un commentaire