6

请看一下这段代码:

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;
}

编译在 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'

基本思想(使用派生类作为基本引用类型参数的默认值)在 Visual Studio 中有效,但在 g++ 中无效。我必须将我的代码发布到他们用 gcc 编译的大学服务器。我能做些什么?有什么我想念的吗?

4

2 回答 2

7

您不能创建对 r 值的(可变)引用。尝试使用常量引用:

 int f(const typename A<T>::base& arg = typename A<T>::derived())
//     ^^^^^

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

 int f(base& arg) {
   ...
 }
 int f() {
   derived dummy;
   return f(dummy);
 }
于 2010-04-16T13:25:13.953 回答
4

您面临的问题是您不能将临时参数用作采用非常量引用的函数的默认参数。临时对象不能绑定到非常量引用。

如果您没有在内部修改对象,则只需将签名更改为:

int f(typename A<T>::base const & arg = typename A<T>::derived())

如果您实际上正在修改传入的参数,则必须使用其他一些技术来允许可选参数,其中最简单的方法是使用可以默认为 NULL 的指针。

于 2010-04-16T13:24:42.220 回答