Sunday, 10 July 2016

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

Guess the output?


template<std::string s>
void PostInArrayNotFound()

int main()
std::string s="Hello";
return 0;


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


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,

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.