Search code examples
c++templatescompile-time-constant

How to make C++ compile time template cast constant?


Is this the only way to initialize default parameter initial_value as a compile time constant of type TNumber? If not, what is the preferred method of doing so?

template <typename TNumber>
class Widget {
 public:
  Widget(TNumber initial_value = static_cast<TNumber>(1))
    : value_(initial_value) {};

 private:
  TNumber value_;
};

Solution

  • The preferred way is to use a type's expected constructor. In C++ 98:

    Widget(TNumber initial_value = TNumber(1));
    

    In C++ 11+ you could use the aggregate constructor as well:

    Widget(TNumber initial_value = TNumber{1});
    

    This also works when your parameter is a const ref, as in

    Widget(const TNumber& initial_value = TNumber{1});
    

    By convention, the explicit default constructor returns 0 for numerical values, so the two following lines are equivalent for the standard numerical types (int, char, float, etc...)

    Widget(const TNumber& initial_value = TNumber{0});
    
    Widget(const TNumber& initial_value = TNumber{});
    

    [EDIT] The same is true for complex numbers (std::complex<>). I suggest you follow the same convention if you ever define your own 'numerical-like' type. It could really save your day at some point.