In the following piece of code, what function will allow the best optimization for an external use and why ? Is the “Version 4” allowed in C++ 2011 ?
template<unsigned int TDIM> class MyClass
{
public:
static inline unsigned int size() {return _size;} // Version 1
static inline const unsigned int size() {return _size;} // Version 2
static constexpr unsigned int size() {return _size;} // Version 3
static inline constexpr unsigned int size() {return _size;} // Version 4
protected:
static const unsigned int _size = TDIM*3;
};
Thank you very much.
I believe that the code in
<random>sets a good example, but also need not be followed slavishly. In<random>you see both of these styles:The choice between 1 and 2 is largely stylistic. They are both resolved at compile time when used in a way that demands a compile-time result. Do you want your clients to type
()or not? Is there generic code that will need to use one style or the other? Satisfying the requirements of generic code is key here.Use of the
inlinekeyword has no impact here. I consider it overly verbose, but it does no harm and has no impact if you use it.Adding
constto a return type will have no impact here. I consider it overly verbose, but it does no harm and has no impact if you use it.If you use the function style, but do not use
constexpr:then this function can not be called at compile-time, and thus can not be used in a context which expects a compile-time constant. That may not cause any harm for your application or your clients if they don’t need such functionality. But imho, if you’ve got
constexprin the toolbox, this is the perfect place to use it. If you do a future client can do stuff like this:These two are equivalent:
but only because the involved type is integral. If the type is not integral, then you have to use
constexprand the type has to have aconstexprconstructor:Everyone here, including myself, is still learning how to use
constexpr. So +1 on the question.