【发布时间】:2014-09-09 17:50:45
【问题描述】:
我正在尝试开发一个通用代码,它可以选择不同的容器类型(std::vector、std::map、其他),并对该容器包装器执行操作,但我遇到了以下代码:
enum class EContainnerType
{
EContainnerType_Normal,
EContainnerType_OR,
EContainnerType_AND
};
// Base declaration
template<EContainnerType, template<class ... > class ContainerType, class ... ArgType >
struct ConditionContainnerType
{
};
// Partial Specialization
template< template<class ... > class ContainerType, class ... ArgType >
struct ConditionContainnerType<EContainnerType::EContainnerType_OR, ContainerType<ArgType ... >, ArgType ...>
{
};
int main()
{
return 0;
}
可变参数模板模板参数没有编译,我得到这个错误:
main.cpp:33:108: error: wrong number of template arguments (2, should be 3)
struct ConditionContainnerType<EContainnerType::EContainnerType_OR,typename ContainerType<ArgType>, ArgType>
^
main.cpp:29:8: error: provided for 'template<EContainnerType <anonymous>, template<class> class ContainerType, class ArgType> struct ConditionContainnerType'
struct ConditionContainnerType
目标:
此实现的主要目标是执行某种分类操作(OR、AND、XOR),此操作是在与通用容器进行比较的元素上执行的。
操作类型由enum class定义,选择部分特化来做操作。
所以,如果我有一个集合 {a,b,c,d,e} 并且我用特定的元素组合填充集合,请说:
generic_container<Operation_type,generic_set_element> 然后我希望通用条件容器执行 “操作类型” 选择的操作。
因此,如果将元素 x 与集合进行比较,通用容器可以对 x 元素执行预选操作。
【问题讨论】:
-
似乎您可能以错误的方式处理此问题。为什么像标准算法那样处理迭代器对的方法不适合您?告诉我们您想要完成什么,而不是您尝试如何完成它。
-
ContainerType模板参数可能会被单个typename替换。如果传递了错误的类型,在使用不存在的类型成员时会出现编译器错误。 -
关于来自 Dark Falcon 的评论,你可以去read about the XY problem。
-
也可能想了解
std::accumulate。我相信它已经可以为你做到这一点了。
标签: c++ templates variadic-templates template-specialization