Sunday, 10 July 2016

Whether user defined objects is allowed as non-type template parameter?

 
Guess the output?

#include<iostream>
#include<string>

template<std::string s>
void PostInArrayNotFound()
{
std::cout<<s<<std::endl;     
}

int main()
{
std::string s="Hello";
PostInArrayNotFound<s>();
return 0;
}

Output:


It will give a compilation error, saying constant expression is required for the non-type template parameter.

EXPLANATION:


First of all, non type template parameter is a compile time constant expression.
What is constant expression?
If a result of the expression is known at compile time, then it is called as constant expression.

Consider the following statement,
6*9/10;

Here value is known at compile time, so it is constant expression. In turn in following statement,
myVar *125;

we are now aware of myVar value. So it is not compile time constant.
Coming to our program, since object s is not a constant expression, compiler will throw an error.

Now you may ask why only constant expression is allowed for non-type template parameter.

Look here for how template works internally.

http://www.arraynotfound.com/2016/07/template-function-or-class-works-internally-cpp.html