派生类作为默认参数 g++
请看一下这段代码:
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 编译它。我能做些什么?我有什么遗漏的吗?
Please take a look at this code:
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;
}
Compiling generates the following error message in 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'
The basic idea (using derived class as default value for base-reference-type argument) works in visual studio, but not in g++. I have to publish my code to the university server where they compile it with gcc. What can I do? Is there something I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您面临的问题是,您不能使用临时参数作为采用非常量引用的函数的默认参数。临时对象不能绑定到非常量引用。
如果您没有在内部修改对象,那么您可以将签名更改为:
如果您实际上正在修改传入的参数,则必须使用其他一些技术来允许可选参数,其中最简单的方法是使用可以默认为 NULL。
The problem you are facing is that you cannot use a temporary as default argument to a function taking a non-const reference. Temporaries cannot be bound to non-const references.
If you are not modifying the object internally, then you can just change the signature to:
If you are actually modifying the passed in argument, you must use some other technique to allow for optional arguments, simplest of which would be using a pointer that can be defaulted to NULL.
您无法创建对右值的(可变)引用。尝试使用 const 引用:
当然,您不能使用 const 引用修改 arg 。如果必须使用(可变)引用,请使用重载。
You cannot create a (mutable) reference to an r-value. Try to use a const-reference:
Of course you can't modify
arg
with a const-reference. If you have to use a (mutable) reference, use overloading.