简体   繁体   中英

non-type template argument

I know that non-type template argument for intgral type must be const expression so:

template <int E>
class cat
{
public:
    int array[E];
};

int main()
{
    cat<4> ob; // ??
}

From what I've read only const variables that get initialized with const expressions are const expressions. In this example, we have int E = 4; , so E will not be a const expression.

So why doesn't cat<4> ob; throw an error? Am I missing something here?
And how will int array[E]; be created if E is not known at compile time?

Whatever you read was rather incomplete.

Constant expressions also include literals (like 4 ), enumerators, sizeof expressions, the results of constexpr functions with constant arguments (since 2011), as well as const variables. Any of these with integer type can be used as an integer template argument.

There are probably a few others that I haven't thought of, and any complex expression built from constant expressions is also a constant expression.

E is 4 before actual compilation starts. Template specialization takes place before that, which means that the code actually seen by the compiler is something like

 class cat4
 {
 public:
 int array[4];
 };

 int main()
 {
 cat4 ob;
 }

This is a fairly loose interpretation, don't take it ad-litteram.

To really test this scenario out, you can try:

 template <int E>
 class cat
 {
 public:
 int array[E];
 };

 int main()
 {
 int k = 4;
 cat<k > ob; // ??
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM