Quantcast
Channel: C++14 Variable Templates: what is their purpose? Any usage example? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by cmaster - reinstate monica for C++14 Variable Templates: what is their purpose? Any usage example?

$
0
0

Well, you can use this to write compile time code like this:

#include <iostream>template <int N> const int ctSquare = N*N;int main() {    std::cout << ctSquare<7> << std::endl;}

This is a significant improvement over the equivalent

#include <iostream>template <int N> struct ctSquare {    static const int value = N*N;};int main() {    std::cout << ctSquare<7>::value << std::endl;}

that people used to write to perform template metaprogramming before variable templates were introduced. For non-type values, we were able to do this since C++11 with constexpr, so template variables have only the advantage of allowing computations based on types to the variable templates.

TL;DR: They don't allow us to do anything we couldn't do before, but they make template metaprogramming less of a PITA.


Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>