从类模板实现纯虚函数 - 参数类型
Implementing pure virtual functions from class template - parameter types
我想创建一个抽象类模板,强制所有实例使用纯虚函数实现doStuff
函数。
我有以下模板:
template<class T>
class X
{
public:
X() {};
virtual ~X() {};
virtual X<T>& doStuff(X<T>& x) = 0;
};
还有一个 T= int 的实例:
class Y : public X<int>
{
public:
Y();
virtual ~Y();
Y& doStuff(Y& x) {
Y res;
Y& res2 = res;
return res2;
}
};
我收到错误消息:
In member function ‘Y& Y::doStuff(Y&)’: cannot declare variable ‘res’ to be of abstract type ‘Y’ because the following virtual functions are pure within ‘Y’: X<T>& X<T>::doStuff(X<T>&) [with T = int]
如果我将参数的类型更改为doStuff
in Y
,一切都很好:
class Y : public X<int>
{
public:
Y();
virtual ~Y();
Y& doStuff(X<int>& x) {
Y res;
Y& res2 = res;
return res2;
}
};
为什么当Y
实现 X 时,参数不能是对Y
对象的引用?
Y&
的返回值不会创建类似的错误消息。
也许我使用了错误的方法来实现我想要的 - 请随时告诉我。
通过将Y&
设置为参数,您可以更改doStuff
的签名,因此res
是抽象的。
即使Y
继承了X
,X<int>&
也不Y&
。
为什么当 Y实现 X 时,参数不能是对 Y 对象的引用?
因为您必须给出在基数的纯虚函数中声明的确切签名。
这就是为什么
class Y : public X<int> {
// ...
X<int>& doStuff(X<int>& x) override;
};
工程。
请参阅工作现场演示。
更不用说返回对局部变量的引用是未定义的行为。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数