简体   繁体   中英

Retrieve default value of in-class initialized member

Is there any way of directly retrieving the default value of a member, which has been defined using in-class initialization? For example:

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' (Similar to decltype ) the entire declaration, including the default value. Does something like that exist?

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

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

which would be used as follows:

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

live demo

This particular case seems to optimize well , but I suggest wariness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM