Get default value for initialized element in class

Is there a way to directly get the default value for a member that was defined using initialization in the class? For instance:

struct Test
{
    int someValue = 5;
};

int main(int argc,char *argv[])
{
    auto val = declvalue(Test::someValue); // Something like this; Should return 5
    std::cout<<val<<std::endl;
    for(;;);
    return 0;
}

Basically something that "copies" (like decltype) the entire declaration, including the default value. Is there something similar?

+4
source share
1 answer

If your default type is constructive, you can write your own declvalue:

template<typename T, typename C>
constexpr T declvalue(T C::* ptr)
{
    return C{}.*ptr;
}

which will be used as follows:

int main() {
    cout << declvalue(&Test::someValue) << endl;
}

live demonstration

This particular case looks optimized well , but I suggest wariness.

+7
source

Source: https://habr.com/ru/post/1659100/


All Articles