如何在C++中将模板与枚举结合起来?

Riz*_*izo 4 c++ enums language-features templates

C++编程语言中有一个巨大的特性集合,可以严格控制数据类型.通常,人们会使用模板系统来模拟他的代码,以实现最合适的功能,同时保证其内部的正确类型保存和操作灵活性.较少使用的枚举用于此目的,因为它们允许为数据定义明确的可能性,并且没有直接的方法来验证类型的正确性.

所以我们拥有的模板允许函数和类使用泛型类型而不需要为每个类型重写; 和枚举,直接使用预期类型.

是否可以使用枚举作为模型为类定义受限制的模板架构?模板化方法如何使用enumed类型以及什么时候有用呢?

我的最后一个问题是:如何结合模板和枚举类型并在抽象数据设计中一起使用它们?

例如,假设您正在尝试创建数据容器,您希望在类中的枚举中定义类型:

template <typename T>
class element
{
public:
  enum type { text_type, widget_type, image_type };

  ...
private:
  type node_type;

};
Run Code Online (Sandbox Code Playgroud)

您还定义了以下各种类型class element:

class text;
class widget;
class image;
Run Code Online (Sandbox Code Playgroud)

要创建元素,您需要指定其内容类型(文本,小部件或图像),以便通过模板参数传递它.

if (node_type == text_type) do_something();
Run Code Online (Sandbox Code Playgroud)

在Java中,您可以List<? extends T>隐式地说明什么类型的类可以用作模板参数.可以使用枚举在C++中完成吗?如何在语句中使用enumed类型?

问题:我想知道如何通过枚举类型来限制模板的行为,以确保只使用这些模板,并使用传统的枚举方式来定位代码.

Unc*_*ens 6

如果您不需要使用枚举,我相信您可以使用标准库中使用的类似技术来对迭代器进行分类.

class text {};
class widget {};
class image {};

struct text_type_tag {};
struct widget_type_tag {};
struct image_type_tag {};

template <class T>
struct element_traits;

template <>
struct element_traits<text>
{
    typedef text_type_tag category;
};

template <>
struct element_traits<widget>
{
    typedef widget_type_tag category;
};

template <>
struct element_traits<image>
{
    typedef image_type_tag category;
};

//add specializations for any other type you want to categorize

//a template that only works with widget types
template <class Widget>
void foo_implementation(Widget w, widget_type_tag);

template <class Widget>
void foo(Widget w)
{
    foo_implementation(w, typename element_traits<Widget>::category());
}

int main()
{
    foo(widget());
    foo(10);  //error, element_traits not specialized for int (incomplete)
    foo(image()); //error, no matching call for foo_implementation(image, image_type_tag);
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是:foo_implementation对其他类别的元素进行重载.


Pot*_*ter 6

@UncleBens说明的类型特征成语是解决此问题的常用方法.

您也可以使用static const整数或枚举类型的成员将信息附加到类.

#include <iostream>

enum color { red, green, blue };

struct x {
    static const color c = red;
};

template< color c >
struct thing;

template<>
struct thing< red > {
    thing() { std::cout << "red\n"; }
};

int main() {
    thing< x::c >();
}
Run Code Online (Sandbox Code Playgroud)