C++ 模板类并强制用户实现某些方法

C++ 模板类并强制用户实现某些方法,c++,stl,C++,Stl,可能重复: 我正在尝试编写C++类模板。我想要的是,当这个类模板与用户定义的类一起使用时,我想要强制这些用户定义的类实现某些方法,例如to_数据和from_数据。我不希望那些用于基本C++原始数据类型。我该怎么做?例如,如果类的复制构造函数不可用,std::vector会给出编译错误。您可以使必须由用户实现的方法成为纯虚拟函数。如果不需要那些用于基本C++原始数据类型,那么可以为这些情况专门化模板并为这些情况提供默认实现。 < P>简单地使用类模板中的方法: template <type

可能重复:


我正在尝试编写C++类模板。我想要的是,当这个类模板与用户定义的类一起使用时,我想要强制这些用户定义的类实现某些方法,例如to_数据和from_数据。我不希望那些用于基本C++原始数据类型。我该怎么做?例如,如果类的复制构造函数不可用,std::vector会给出编译错误。

您可以使必须由用户实现的方法成为纯虚拟函数。如果不需要那些用于基本C++原始数据类型,那么可以为这些情况专门化模板并为这些情况提供默认实现。

< P>简单地使用类模板中的方法:

template <typename T>
struct Serializer
{
    void serialize(T const & t) const { write(t.to_data()); }
    void deserialize(T & t) const { t.from_data(read()); }
};
然而,这意味着为每个特定类型编写专门化,即使其中一些类型实际上是以相同的方式处理的

一个不那么麻烦的解决方案是使用类型特征,并根据本例中参数类型的某些特征选择正确的实现,无论它们是否原始:

#include <type_traits>

template <typename T, typename Enable = void>
struct Serializer
{
    // same as before
};

// Partial specialization for fundamental types
template <typename T>
struct Serializer<T, typename 
    std::enable_if<std::is_fundamental<T>::value>::type>
{
    void serialize(T t) const { write(t); }
    void deserialize(T & t) const { t = read(); }
};

Serializer<Foo> sf; // first implementation
Serializer<int> si; // second (specialized) implementation

什么是只声明一些虚拟方法签名而没有定义?您还可以声明纯虚拟方法:virtualvoid my_methodargs=0@iammilind:我不认为这是一个重复。事实上,这两个Q都是几乎不相关的AFAIC。@看起来很相似,但这个问题确实增加了额外的扭曲,即不需要基本类型的方法。所以必须为所有基本类型提供专门化?听起来需要做很多工作。这样做意味着类模板只能用于派生自公共基类(定义纯虚拟成员函数的基类)的类型。这或多或少违背了最初使用模板的目的。
template <>
struct Serializer<int>
{
    void serialize(int i) const { write(i); }
    void deserialize(int & i) const { i = read(); 
};
#include <type_traits>

template <typename T, typename Enable = void>
struct Serializer
{
    // same as before
};

// Partial specialization for fundamental types
template <typename T>
struct Serializer<T, typename 
    std::enable_if<std::is_fundamental<T>::value>::type>
{
    void serialize(T t) const { write(t); }
    void deserialize(T & t) const { t = read(); }
};

Serializer<Foo> sf; // first implementation
Serializer<int> si; // second (specialized) implementation