【问题标题】:derived class as default argument g++派生类作为默认参数 g++
【发布时间】:2011-02-08 20:07:16
【问题描述】:

请看一下这段代码:

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 编译的大学服务器。我能做些什么?有什么我遗漏的吗?

【问题讨论】:

  • 没有解决错误,但你可以写int f(base&amp; arg = derived())

标签: c++ templates g++ default-value derived


【解决方案1】:

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

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

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

 int f(base& arg) {
   ...
 }
 int f() {
   derived dummy;
   return f(dummy);
 }

【讨论】:

  • 谢谢大家,这解决了我的问题。 const版本就够了,在真实的上下文中,base是一个比较事物的谓词类,所以我不需要修改它。
  • 你被 Visual Studio 扩展绊倒了,编译时打开警告级别 4,它应该会触发。
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2022-01-17
    相关资源
    最近更新 更多