我想根据传递给类的模板参数实现一个Implementation开关:
我调整了我的代码,以便能够通过这里提到的技巧隐藏类DataElement中的类方法 C++: Enable method based on boolean template parameter
我确实得到了以下错误,同时根据我的问题调整了这个技巧:
错误:无法将变量'dataEle'声明为抽象类型 “DataElement”
testEnableIF.h
#ifndef TESTENABLEIF_H_
#define TESTENABLEIF_H_
#include <iostream>
#include <type_traits>
/// @brief some dummy class to mark a type as Serializable
class Serializable {};
/// @brief abstract base class which adds additional abilities to DataElement
class SerializableElement {
public:
virtual void unloadTo(int x) =0;
virtual void loadFrom(int x) =0;
};
/// @brief used by the DataElement class
class DisableSerializability {};
/// @brief is a container class which manages the creation and
/// access to a data element of type _DataType
template< typename _DataType, bool _IsDataSerializable = std::is_base_of<Serializable,_DataType>::value >
class DataElement :
// derive from SerializableElement, only if the template type _DataType is derived from the interface Serializable
public
std::conditional<
_IsDataSerializable,
SerializableElement, // add additional properties to DataElement if its Serializable
DisableSerializability >::type {
public:
DataElement(): m_content(new _DataType()){}
void foo(int x) { std::cout << "in foo" << std::endl; }
template <bool _EnabledAbility = _IsDataSerializable>
void unloadTo(typename std::enable_if<_EnabledAbility, int>::type x)
{ std::cout << "in unloadTo" << std::endl; }
template <bool _EnabledAbility = _IsDataSerializable>
void loadFrom(typename std::enable_if<_EnabledAbility, int>::type x)
{ std::cout << "in loadFrom" << std::endl; }
private:
_DataType* m_content;
};
#endif /* TESTENABLEIF_H_ */
调用类DataElement
的测试代码的main.cpp
#include "testEnableIF.h"
class SerializableType : public Serializable {
int x;
int y;
int z;
};
class NonSerializableType {
int u;
};
int main() {
SerializableType sType;
NonSerializableType nType; // other type without being derived from Serializables
DataElement<SerializableType> dataEle;
dataEle.unloadTo(3);
return 0;
}
答案 0 :(得分:1)
template <bool _EnabledAbility = _IsDataSerializable>
void unloadTo(typename std::enable_if<_EnabledAbility, int>::type x);
不是
的覆盖virtual void unloadTo(int x) = 0;
您甚至可以通过添加override
来获取错误。
修复的方法是从一个继承自SerializableElement
的具体类继承而不是仅从接口继承。