使用SFINAE检查该类是否相同或是从C++98中的另一个模板类派生的
Using SFINAE to check whether the class is same or is derived from another template class in C++98
我正在尝试读取STL集合,并以更有效的方式为那些具有resize()
和operator[]()
方法而不是使用std::insert_iterator
的集合分配内存。我还定义了几个非STL集合,它们看起来像STL集合,但事实并非如此(有些函数可能无法实现,例如insert(iterator, const_reference)
和我根本无法使用std::insert_iterator
)。
我已经编写了以下读取集合的函数:
template<typename TSTLCollection>
void ReadCollection(TSTLCollection* pCollection)
{
ReadingCollectionFunctorClass<
STLCollectionShouldBeResizedAndReadByIndex<TSTLCollection>::value
>(pCollection);
}
我有一个函子模板ReadingCollectionFunctorClass<bool>
,它对true
和false
值有两个专门化。它们都实现了模板成员功能
template<typename TSTLCollection>
void operator()(TSTLCollection*);
我接下来要检查的是必须调用这些专业中的哪一个。为了存档,我写了这个类:
template<typename TSTLCollection>
struct STLCollectionShouldBeResizedAndReadByIndex
{
private:
template<typename TItem>
static char f(NonSTLCollection<TItem>* pCollection, int);
template<typename TItem>
static char f(std::basic_string<TItem>* pCollection, int);
template<typename TItem>
static char f(std::vector<TItem>* pCollection, int);
template<typename TCollection>
static long f(TCollection* pCollection, ...);
public:
enum { value = sizeof(f((TSTLCollection*)0, int())) == sizeof(char) };
};
如果我调用ReadCollection(pStlCollection)
,一切都很好,但问题是,如果我调用ReadCollection(pClassDerivedFromStlCollection)
,它就不起作用:对于派生类,STLCollectionShouldBeResizedAndReadByIndex
没有value == true
。出了什么问题,我应该如何解决?
我不能使用C++11或C++14功能,只能使用C++98。我不能使用boost和其他第三方库
不确定我是否清楚地理解您的意图:
template <typename TSTLCollection>
struct STLCollectionShouldBeResizedAndReadByIndex
{
private:
template <typename TItem>
static char f(NonSTLCollection<TItem>* pCollection);
template <typename TItem>
static char f(std::basic_string<TItem>* pCollection);
template <typename TItem>
static char f(std::vector<TItem>* pCollection);
static long f(...);
public:
enum { value = sizeof(f((TSTLCollection*)0)) == sizeof(char) };
};
现场演示
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 在 C++ 中用派生类型重写成员函数
- 具有多个类、派生类的C++正向声明
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如果基类包含双指针成员,则派生类的构造函数
- 使用SFINAE检查该类是否相同或是从C++98中的另一个模板类派生的
- C++'98 - 将基类转换为派生类