简体   繁体   English

MSVC12中不允许使用默认参数中的模板类实例化吗?

[英]Template class instantiation in default parameter not allowed in MSVC12?

I just extracted the following problem in our project. 我只是在我们的项目中提取了以下问题。 The following code just compiles fine with g++ 以下代码使用g ++即可正常编译

#include <vector>

class A {};

typedef std::vector<A*> vec_t;

class bar {
public:
  bar(vec_t) {};
};

class foo
{
public:
  foo(bar* a = new bar(vec_t())) {};
};

class B
{};

int main()
{
  return 0;
}

However, the Visual Studio Compiler (VC12, but I presume all others too) doesn't understand that in the default argument for the c'tor of foo the c'tor of bar is called which takes an instance of a vector as an argument. 然而,在Visual Studio编译器(VC12,但我相信所有其他的也行)不明白,foo的 酒吧的c'tor叫的c'tor默认参数,这需要载体的实例作为参数。 This causes an error for every class/struct declared after this expression: 这将导致在此表达式之后声明的每个类/结构均出错:

error C2462: 'B' : cannot define a type in a 'new-expression'

I don't want to discuss the software design of the c'tor, but is this a compiler issue or just not allowed in standard C++ and the g++ just not being strict about that? 我不想讨论c'tor的软件设计,但这是编译器问题,还是在标准C ++中是不允许的,而g ++对此并不严格?

First, I thought that a template-instantiation in a default parameter may be not allowed or nested c'tors in a default argument. 首先,我认为可能不允许默认参数中的模板实例化或将默认参数嵌套在模板中。 However, if I use another c'tor of the vector: 但是,如果我使用向量的另一个c'tor:

foo(bar* a = new bar(vec_t(0))) {}

it compiles with MSVC. 它与MSVC一起编译。 I just can't see why the upper version shouldn't compile? 我只是看不到为什么不应该编译较高版本? Any thoughts on that? 有什么想法吗?

It looks like this is an issue with the "most vexing parse" (see the Wikipedia article on it for more info). 看来这是“最烦人的解析”问题(有关更多信息,请参见其上的Wikipedia文章)。 One way to disambiguate the new expression is to add parentheses around the constructor like this 消除新表达式歧义的一种方法是像这样在构造函数周围添加括号

foo(bar* a = new bar((vec_t()))) {};

When it comes to standards compliance I'm not sure. 关于标准合规性,我不确定。 I skimmed section 6.8 (Ambiguity Resolution) and 5.3.4 (New) of N3690 and without thinking about it too hard nothing stood out either way. 略读了N3690的 6.8节(歧义度解决方案)和5.3.4节(新),并且没有想太多,没有任何办法脱颖而出。 Maybe a real language lawyer will need to step in to give an answer. 也许一位真正的语言律师将需要介入以给出答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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