纯虚拟方法的模板专业化
Template specialization of pure virtual method
期望此代码编译并工作
template<class T>
class Base
{
virtual void method() = 0;
};
template<>
void Base<int>::method() { std::cout << "overrided" << std::endl; }
Base<int> base;
但它给出了'Base<int>': cannot instantiate abstract class
错误。认为部分专业化将使Base<int>
非抽象并允许实例化它。
有没有像这个一样短的工作解决方案,并使Base
类保持抽象?否则,我可以使Base
类非抽象或使用Nicol Bolas的解决方案:模板专用化和继承
如果它不适用于非模板类,为什么它适用于模板类?
#include<iostream>
class Base
{
virtual void method() = 0;
};
void Base::method() { std::cout << "overrided" << std::endl; }
Base base;
错误:
10 : error: cannot declare variable 'base' to be of abstract type 'Base'
Base base;
^
3 : note: because the following virtual functions are pure within 'Base':
class Base
^
8 : note: virtual void Base::method()
void Base::method() { std::cout << "overrided" << std::endl; }
^
Compilation failed
整个类的专业化(而不仅仅是一个成员函数)呢:
template<class T>
struct TempClass
{
virtual void f() = 0;
};
template <>
struct TempClass<int>
{
virtual void f()
{
//...
}
};
注意TempClass<int>
不再是抽象类,但其他Base
类仍然是抽象类(TempClass<float>
、TempClass<double>
、TempClass<SomeClassType>
、...
)。
和
它不会包含泛型类TempClass
包含的字段。您将不得不从通用 Base 复制粘贴它们,或者,这是更聪明的解决方案,
您将使用两个专用化都具有的字段创建基类,然后使这些模板类继承自该基类:
template <typename T>
struct Base
{
// some members that all Base classes have
};
template <typename T>
struct TempClass: Base<T>
{
virtual void f() = 0;
};
template <>
struct TempClass<int>: Base<int>
{
virtual void f()
{
//...
}
};
这样就不需要丑陋的复制粘贴了。
可以在类中提供纯虚函数的实现。这不会使类可实例化。
class Base
{
virtual void method() = 0;
};
void Base::method() { /* Do something */ }
// This is still a problem since Base
// is still an abstract class, i.e. it is not still not
// instantiable.
Base base;
相关文章:
- 如何使用默认参数等选择模板专业化
- 虚拟决赛作为安全
- 模板化建造师专业化
- PowerPC ppc64le上的Gcc Woverloaded虚拟错误
- 类模板的成员功能的定义在单独的TU中完全专业化
- 如何在C++中获得"静态纯虚拟"功能?
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 部分专业化和嵌套模板
- 模板专业化可以进入我的.cpp吗?
- 大小虚拟继承中的派生类
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 使用 C++ 和 i2c 工具从虚拟 i2c 写入和读取
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 派生类中纯虚拟基方法的专业化
- 纯虚拟方法的模板专业化