AlexDan
AlexDan

Reputation: 3351

Non-type template Arguments

I was reading an article about non-type template arguments, and it said that :

When being instantiated, only compile time constant integer can be passed. This means 100, 100+99, 1<<3 etc are allowed, since they are compiled time constant expressions. Arguments, that involve function call, like abs(-120), are not allowed.

Example :

template<class T, int SIZE>
class Array{};

int main(){
Array<int, 100+99> my_array; // allowed
Array<int, abs(-120)> my_array; // not allowed
}

what's the difference between 100+99 and abs(-120) ?
how come 100+99 are compiled time and abs(-120) is not?

Upvotes: 2

Views: 363

Answers (2)

Puppy
Puppy

Reputation: 147018

None, and abs(-120) is entirely legal in C++11. C++03, as you adequately point out, did not have scope for functions which could evaluate at compile-time, but C++11 does. For abs directly, you could replace it with a template which performs the same computation and use abs_template<-120>::value in C++03.

Edit: I meant to say that, even if abs was not constexpr, you could trivially write your own abs which is constexpr. Coulda sworn I edited that in.

Upvotes: 4

Griwes
Griwes

Reputation: 9039

100+99 is optimized out to 199 at compile time.

abs() is function and it may or may not be marked constexpr (C++11 feature, that would allow you to do so; you can easily check cppreference or standard to see if it's constexpr in C++11). It requires to be executed; compiler cannot deduce that it's state less function returning same value for every run with same argument.

Upvotes: 3

Related Questions