Gotcha
Gotcha

Reputation: 392

C++ template type specification

I have an empty class with the same name as a blank function. When I try to pass this class as a template parameter I receive an error:

"type/value mismatch at argument 1"

"'Test' is not a valid template type argument for parameter '_Ty'"

Consider:

#include <vector>

void Test() {
}

class Test {
};

int main() {
    std::vector<Test> test;
}

Changing to

std::vector<class Test>

seems to work, but I was not able to found out, whether this is required by a standard, or just randomly supported by my compiler.

Can someone point out, how to solve this issue or link to standard, that requires this behavior?

Upvotes: 2

Views: 417

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

Yes you have to use the keyword class prepended to the name for disambiguation, which resulting in an elaborated type specifier.

[class.name]/2:

(emphasis mine)

If a class name is declared in a scope where a variable, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier ([basic.lookup.elab]). [ Example:

struct stat {
  // ...
};

stat gstat;                     // use plain stat to define variable

int stat(struct stat*);         // redeclare stat as function

void f() {
  struct stat* ps;              // struct prefix needed to name struct stat
  stat(ps);                     // call stat()
}

— end example ]

And [dcl.type.elab]:

elaborated-type-specifier:

  • class-key attribute-specifier-seqopt nested-name-specifieropt identifier
  • class-key simple-template-id
  • class-key nested-name-specifier templateopt simple-template-id
  • enum nested-name-specifieropt identifier

Upvotes: 4

Related Questions