纯虚拟方法的模板专业化

Template specialization of pure virtual method

本文关键字:专业化 虚拟 方法      更新时间:2023-10-16

期望此代码编译并工作

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;