简体   繁体   中英

member function that is not const should only be constexpr if on C++14 or later

In C++11, constexpr on a member function implies const. That was changed in C++14.

I have some code that has a member function that should be constexpr, but cannot be const, so I'd like it to be constexpr if compiled with std c++14 or later. One way to do this is:

class Foo {
#if _cplusplus >= 201402L
    constexpr
#endif
    int baz(const Bar& bar);
};

Is there a better way to express this, preferably without the preprocessor?

The best way to do it would be to take advantage of the Feature-test Macros, as part of SD-6 . The change that constexpr member functions are not implicitly const is marked as __cpp_constexpr having value 201304 . So that should be your test:

class Foo {
#if __cpp_constexpr >= 201304L
    constexpr
#endif
    int baz(const Bar& bar);
};

Which if you do this for more than one member function, you probably want to generalize to:

#if __cpp_constexpr >= 201304L
#  define CONSTEXPR_MEM constexpr
#else
#  define CONSTEXPR_MEM
#endif

class Foo {
    CONSTEXPR_MEM int baz(const Bar& bar);
};

The way you present it in the question (using __cplusplus ) is perfectly valid - the advantage of the feature-test macros is that different compiles adopt various features at different stages, so you can get a more granular, accurate test. Going forward, all the major vendors have agreed that SD-6 is the right direction and that will be the way to do things in the future.

Note that there is no way to express this without the preprocessor. There is no conditional constexpr . There is just constexpr .

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