Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is a variable template

I am getting c++11 warnings about variable templates. I'm not entirely sure that I need them, because I'm not entirely sure what they are. References that I've found don't bother defining the term before using it. My immediate thought was that it was an attempt to declare a variable that is of the templated type T, but this code compiles fine:

template <class T>
image<T> *image<T>::copy() const {
  image<T> *im = new image<T>(w, h, false);
  memcpy(im->data, data, w * h * sizeof(T));
  return im;
}

What is a thorough definition of a variable template, and why does this NOT have a variable template problem

like image 403
Him Avatar asked May 19 '26 09:05

Him


1 Answers

A class template is a template that defines a series of classes, based on one or more template parameters. A function template is a template that defines a series of functions, based on one or more template parameters. vector is a template class; vector<int> is a specific class instantiated from that template.

A variable template is therefore a template that defines a series of variables, based on one or more template parameters:

template<typename T>
T variable_name{};

That is a variable template. You would specify which one you want just like any other template: variable_name<int> will be of type int. variable_name is a template; variable_name<int> is actually a variable.

Of course, you can do more complex things:

template<typename T>
vector<T> vector_var{};

vector_var<int> is a vector<int>.

Variable templates can only be introduced at namespace/global scope and as static members of classes. At namespace/global scope, they're usually declared constexpr (and/or in C++17, inline). They're useful for making constants:

template<typename T>
inline constexpr bool is_default_constructible_v = std::is_default_constructible<T>::value;

So if you want to tell if something is default constructible, you don't need the slightly awkward ::value syntax.

Variable templates are a C++14 feature, which is why your compiler probably warned you about using them in a C++11 mode.


image<T> *im = new image<T>(w, h, false);

This is not a variable template. This is a regular variable whose type is very well defined: image<T>. There is exactly one variable named "im". You don't use im<T> to get a variable.

That statement does not define a family of variables. What you have is a family of functions, where each of them contain a variable called im. The function is the template here, not the variable.

like image 68
Nicol Bolas Avatar answered May 21 '26 00:05

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!