类标志的模板专门化
Template specialization for class flags
我想知道下面的部分专门化,在这里我基于一个泛型List模板定义有序和无序列表,是否是正确的,有效的方法。
template <typename T, bool O> class List;
template <typename T> class UList: public List<T,false>{};
template <typename T> class OList: public List<T,true>{};
谢谢,
对于这样的内容,我会使用策略类来定义如何将内容插入到单个列表中,例如
struct DefaultInsertionPolicy
{
template <typename ContainerType, typename ValueType>
static void insert(ContainerType& container, ValueType const& cValue)
{
container.insert(container.end(), cValue);
}
};
struct SortedInsertionPolicy
{
template <typename ContainerType, typename ValueType>
static void insert(ContainerType& container, ValueType const& cValue)
{
// I'm using lower_bound here, but do what is necessary for you
typename ContainerType::iterator ft = std::lower_bound(container.begin(), container.end(), cValue);
container.insert(ft, cValue);
}
};
template <typename T, typename InsertPolicy = DefaultInsertionPolicy>
class List
{
:
// insert function
void insert(T const& cValue)
{
InsertPolicy::insert(*this, cValue); // delegate to the policy to do the insert
}
void insert(iterator iPos, T const& cValue)
{
// do the real insertion at the provided position.
}
};
所以实类型可以是
typedef List<some_type> UList; // insertion order
typedef List<some_type, SortedInsertionPolicy> OList; // sorted list
我认为您希望通过减少用户最终将在其代码中使用的类的模板参数的数量来降低类模板的泛型。如果是这样,那么在c++ 03和c++ 98中,您可以这样做,即定义从更泛型的类派生的不那么泛型的类。
然而,在c++ 11中,不需要定义新的类模板。相反,您可以创建模板别名,减少模板参数的数量,同时:
template <typename T>
using UList = List<T,false>;
template <typename T>
using OList = List<T,true>;
使用UList
和OList
,就好像它是一个类模板,接受一个类型参数:
UList<int> uints;
OList<float> ofloats;
在wiki中,我刚刚学会了这种定义类型/别名的新方法,这是我们以前使用typedef
来做的:
using语法也可以用作c++ 11中的类型混叠:
typedef void (*Type)(double); // Old style using OtherType = void (*)(double); // New introduced syntax
相关文章:
- 是否可以对零模板参数进行模板专门化
- 即使使用调试编译标志,表达式也是"optimized out"
- 在 CMake 中为每个目标设置编译器/链接器标志
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何基于模板化类的基类专门化成员函数
- File.cpp.o:OpenPose 标志 CMakeFiles/.. 的多重定义/main.cpp.o:首先在这里定
- 在轮班操作后使用携带标志
- 如何找出引入AVX标志的内容
- I2C 文件描述符上的 I2C 总线可写/可读标志
- C ++是否有C ++ 17 OSX 10.13.6的标志
- 每次使用带有LOCK_EX标志的LOCK_NB时,相同的程序/进程都会获取锁
- 如何为指向复杂值的迭代器专门化算法?
- CMake 3.5 中的链接器标志位置
- 如何使用 gnu gcc 标志 -mpc32、-mpc64 和 -mpc80?
- 专门化模板覆盖函数/避免对象切片
- 在 CMake 中添加全局编译标志
- -Wlifetime 标志的目的是什么?
- 我能否根据其运算符()的签名专门化可变参数模板参数
- Visual Studio 19-17 库兼容性根据 GL 标志
- 类标志的模板专门化