[英]C++ template member function having pointer reference template parameter
class BI {
public:
virtual void fun() = 0;
virtual ~BI() {}
};
class B : public BI {
public:
void fun() {}
};
template <typename T>
class A {
T* obj;
public:
void funT(const T*&) /* adding reference is creating error */;
};
template <typename T>
void A<T>::funT(const T*& obj) {
}
int main() {
A<B> obj;
obj.funT(new B());
}
当使用g ++编译器编译以上代码时,出现错误: 没有匹配的函数调用A :: funT(B )*。 但是,当我从funT()声明中删除引用' & '运算符作为void funT(const T* obj)
,它可以编译并正常工作。 为什么这里不允许引用运算符?
您需要的是对指针的引用 ,您将无法获得对临时值的引用(除非它们是C ++ 11 rvalue引用)。
确保您将左值作为参数传递,以使引用正常工作。
例如
#include <iostream>
using namespace std;
class BI {
public:
virtual void fun() = 0;
virtual ~BI() {}
};
class B : public BI {
public:
void fun() {}
};
template <typename T>
class A {
T* obj;
public:
void funT(const T*&);
};
template <typename T>
void A<T>::funT(const T*& obj) {
}
int main() {
A<B> obj;
const B* ptr = new B(); // <-- This is an lvalue
obj.funT(ptr);
delete ptr; // Also clean it up after you used it
}
这是一个显示相同问题的更简单的程序:
void fun(const int*&) {}
int main() {
int x;
fun(&x);
}
它产生以下错误:
invalid initialization of non-const reference of type ‘const int*&’
from an rvalue of type ‘int*’
那讲得通。 fun
接受类型为“对指向const int
非const指针的引用”的参数,我们尝试将其传递为“ pointer to int
”的临时类型。 对非const类型的引用不会绑定到临时对象,因为临时对象通常是不可变的。 在这种情况下,如果允许我们将&x
作为参数传递给fun
,则fun
将能够修改x
的地址,这没有任何意义。
如您所见,删除&
可使代码格式正确:
void fun(const int*) {}
现在,我们只是将指针传递给int
,而该指针的类型值将指向const int
,这是一个简单的隐式转换。
或者,你可能已经用于fun
采取型的“参考const的指针参数int
”:
void fun(int* const&) {}
或对指向const int
const指针的引用:
void fun(const int* const&) {}
但是对const指针的引用有点愚蠢,因为简单的指针也一样。
最后,您可以保留fun
的原始声明,而避免尝试传递一个临时变量作为其参数。
错误消息已清除。 参数类型是指向T的指针的引用 ,但是您正在发送指向T的指针 。 在这种情况下,不能将临时消息作为参考传递。 你可以写:
int main() {
A<B> obj;
const B* b=new B(); //create a lvalue
obj.funT(b);
delete b; // make sure to release memory.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.