Sunday, 10 July 2016

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

No comments:
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.

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

Look here for how template works internally.

No comments:

Post a Comment