派生类作为默认参数g ++

Vin*_*ent 6 c++ templates g++ derived default-value

请看一下这段代码:

template<class T>
class A
{
 class base
 {

 };

 class derived : public A<T>::base
 {

 };

public:

 int f(typename A<T>::base& arg = typename A<T>::derived())
 {
  return 0;
 }
};

int main()
{
 A<int> a;
 a.f();
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译在g ++中生成以下错误消息:

test.cpp: In function 'int main()':
test.cpp:25: error: default argument for parameter of type
                    'A<int>::base&' has type 'A<int>::derived'
Run Code Online (Sandbox Code Playgroud)

基本思想(使用派生类作为base-reference-type参数的默认值)在visual studio中工作,但在g ++中不起作用.我必须将我的代码发布到他们使用gcc编译它的大学服务器.我能做什么?有什么我想念的吗?

ken*_*ytm 7

您无法创建对r值的(可变)引用.尝试使用const-reference:

 int f(const typename A<T>::base& arg = typename A<T>::derived())
//     ^^^^^
Run Code Online (Sandbox Code Playgroud)

当然你不能arg用const-reference 修改.如果必须使用(可变)引用,请使用重载.

 int f(base& arg) {
   ...
 }
 int f() {
   derived dummy;
   return f(dummy);
 }
Run Code Online (Sandbox Code Playgroud)

  • 你已经被Visual Studio扩展程序绊倒了,使用警告级别4进行编译,它应该触发它. (2认同)