C++ template type specification

六月ゝ 毕业季﹏ 提交于 2019-12-24 01:07:26

问题


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?


回答1:


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 templateoptsimple-template-id
  • enum nested-name-specifieropt identifier


来源:https://stackoverflow.com/questions/50436381/c-template-type-specification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!