i am trying to learn templates in c++. Can someone please explain why sq() works and add() does not? How can add() be fixed? What is use of non type templates?
template <typename T>
inline T sq (const T& x)
{
return x*x;
}
template <int*>
inline int add(int* x)
{
return (*x)*2;
}
int main() {
int x = 2;
cout<<"Square(2): "<<sq(2)<<" Add(2): "<<add(&x)<<endl;
return 0;
}
Even after modifying the above example as below, it would still Not work
template <typename T>
inline T sq (const T& x)
{
return x*x;
}
template <int>
inline int add(int x)
{
return x+x;
}
int main() {
cout<<"Square(2): "<<sq(2)<<" Add(2): "<<add(2)<<endl;
return 0;
}
I’m not quite sure what you’re asking, but you could use a non-type template parameter to, for example, define a function template that adds any compile-time constant to its argument:
To answer your specific question about why
sq(2)compiles butadd(&x)doesn’t: type parameters of function templates can be deduced from the function arguments. Sosq(2)is equivalent tosq<int>(2). Non-type parameters can’t be deduced, so you have to provide one. In the case of a pointer parameter, the argument must be a pointer to a variable with external linkage, so the following should compile: