1

I came to know about C++14 comes with variable template.

 template<typename T>
    constexpr T pi = T(3.1415926535897932385);

My question is - When we use variable templates over normal variable? Please Give me some example.

Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • 2
    Isn't that an example ? – Quentin Aug 20 '14 at 17:42
  • Have you looked at http://stackoverflow.com/questions/21051141/c14-variable-templates-what-is-the-purpose-any-usage-example – sfjac Aug 20 '14 at 17:43
  • A simple example would be a list of elements (where element is a templated type). I.e. templates make it possible to generalize a class for different types which prevents code duplication. – cageman Aug 20 '14 at 17:45

1 Answers1

3

One of the properties of templates is support of explicit (and partial) specializations. I'd guess that this would apply to variable templates as well, allowing you to provide individual initializers for different specializations, as in

template<typename T>
  constexpr T pi = T(3.1415926535897932385);

template<>
  constexpr float pi = 3.1415;

template<>
  constexpr MyFractionType pi = MyFractionType(22, 7); // close enough for most purposes

template<>
  constexpr int pi = 3; // :)

As it's been mentioned in the comments, it is already possible to "templatize and specialize variables" by wrapping them into a class (as static members). Variable templates would allow one to do that without resorting to a class-wrapper-based workaround. In that sense, template variables solve the same issues as template typedefs do.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765