【问题标题】:Template class instantiation in default parameter not allowed in MSVC12?MSVC12 中不允许默认参数中的模板类实例化?
【发布时间】:2013-11-27 04:28:54
【问题描述】:

我刚刚在我们的项目中提取了以下问题。下面的代码用 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;
}

但是,Visual Studio 编译器(VC12,但我认为所有其他编译器也是如此)不理解在 foo 的 c'tor 的默认参数中 的 c'tor bar 被调用,它将向量的实例作为参数。这会导致在此表达式之后声明的每个类/结构都会出错:

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

我不想讨论 c'tor 的软件设计,但这是编译器问题还是标准 C++ 中不允许,而 g++ 对此并不严格?

首先,我认为默认参数中的模板实例化可能不允许或默认参数中嵌套 c'tors。但是,如果我使用另一个向量的 c'tor:

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

它使用 MSVC 编译。我只是不明白为什么上版本不应该编译?对此有什么想法吗?

【问题讨论】:

  • 试试new bar((vect_t())) {}

标签: c++ templates visual-c++ compiler-errors default-parameters


【解决方案1】:

看起来这是“最令人烦恼的解析”的问题(有关更多信息,请参阅Wikipedia 文章)。消除新表达式歧义的一种方法是像这样在构造函数周围添加括号

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

谈到标准合规性,我不确定。我浏览了N3690 的第 6.8 节(歧义解决)和 5.3.4(新),没有想太多,两种方法都没有突出。也许真正的语言律师需要介入给出答案。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多