派生类作为默认参数g ++ [英] derived class as default argument g++
问题描述
模板< class T>
class A
{
class base
{
};
class derived:public A< T> :: base
{
};
$ b public:
int f(typename A< T> base& arg = typename A< T> :: derived())
{
返回0;
}
};
int main()
{
A< int>一个;
a.f();
返回0;
$ / code>
编译会在g ++中产生以下错误信息:
test.cpp:在函数'int main()'中:
test.cpp:25:error:参数类型为$ b的缺省参数$ b'A< int> base&'类型为'A< int> :: derived'
基本思想(使用派生类作为base-reference-type参数的默认值)在visual studio中工作,但不在g ++中。我必须将我的代码发布到大学服务器,然后用gcc编译它。我能做什么?是否有我缺少的东西?
您无法创建对r值的(可变)引用。尝试使用const引用:
int f(const typename A< T> base& arg = typename A< T> :: derived())
// ^^^^^
当然你不能用const引用修改 arg
。
int f(base& arg){
...
}
int f(){
派生虚拟;
返回f(虚拟);
}
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?
You cannot create a (mutable) reference to an r-value. Try to use a const-reference:
int f(const typename A<T>::base& arg = typename A<T>::derived())
// ^^^^^
Of course you can't modify arg
with a const-reference. If you have to use a (mutable) reference, use overloading.
int f(base& arg) {
...
}
int f() {
derived dummy;
return f(dummy);
}
这篇关于派生类作为默认参数g ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!