c++ - 将不同枚举类类型作为输入的函数,怎么样?

我面临以下问题。假设我有两个(或更多)这样的枚举类:

enum class CURSOR { ON, OFF };
enum class ANSI { ON, OFF };

我正在尝试实现一个名为 OPTION 的(模板)函数,它能够执行如下操作:

OPTION( CURSOR::ON );
OPTION( ANSI::ON );

我试过这样实现:

template <typename T>
inline void OPTION( const T& opt )
 {
  if( opt == CURSOR::ON ) //do something...;
  else if( opt == CURSOR::OFF ) //do something...; 
  else if( opt == ANSI::ON ) //do something...;
  else if( opt == ANSI::OFF ) //do something...;
 }

但是如果我尝试编译之前定义的两行代码,它会给我以下错误:

examples/../include/manipulators/csmanip.hpp: In instantiation of 'void osm::OPTION(const T&) [with T = CURSOR]':
examples/manipulators.cpp:190:14:   required from here
examples/../include/manipulators/csmanip.hpp:88:18: error: no match for 'operator==' (operand types are 'const osm::CURSOR' and 'osm::ANSI')
   88 |     else if( opt == ANSI::ON ) enableANSI();
      |              ~~~~^~~~~~~~~~~
examples/../include/manipulators/csmanip.hpp:88:18: note: candidate: 'operator==(osm::ANSI, osm::ANSI)' (built-in)
examples/../include/manipulators/csmanip.hpp:88:18: note:   no known conversion for argument 1 from 'const osm::CURSOR' to 'osm::ANSI'
examples/../include/manipulators/csmanip.hpp:88:18: note: candidate: 'operator==(osm::CURSOR, osm::CURSOR)' (built-in)
examples/../include/manipulators/csmanip.hpp:88:18: note:   no known conversion for argument 2 from 'osm::ANSI' to 'osm::CURSOR'
examples/../include/manipulators/csmanip.hpp:89:18: error: no match for 'operator==' (operand types are 'const osm::CURSOR' and 'osm::ANSI')
   89 |     else if( opt == ANSI::OFF ) disableANSI();

请忽略我在代码中的命名空间 osm 中定义它们的事实。

您知道问题是什么吗?您是否知道如何构建适用于此任务的函数?谢谢。

最佳答案

一个选择是编写多个重载函数,每个函数处理不同的枚举类型。例如:

void OPTION(CURSOR c) {
    switch (c) {
        case CURSOR::ON:  /* turn cursor on */;  break;
        case CURSOR::OFF: /* turn cursor off */; break;
    }
}

void OPTION(ANSI a) {
    switch (a) {
        case ANSI::ON:  /* turn ANSI on */;  break;
        case ANSI::OFF: /* turn ANSI off */; break;
    }
}

然后重载解析将选择正确的函数来调用:

OPTION(CURSOR::OFF); // Calls first function
OPTION(ANSI::ON);    // Calls second function   

https://stackoverflow.com/questions/72746726/

相关文章:

r - 在整个数据帧上使用 ifelse()

c - 为什么 putchar(1 +'0' ) 不输出 10?

amazon-ec2 - 一个 Amazon EC2 实例可以服务多少用户?

php - 过滤消息的内容上的单词黑名单

csv - 使用 Sed、Awk 等将第一列中每一行的数据复制到最后一列中的 html 超链接中

.net - Session.Timeout 和 Server.ScriptTimeout 有什么区

c# - 等待似乎没有按顺序执行

java - 为什么 LocalDateTime.ofInstant() 需要 ZoneId

c# - 我如何编写介于两个值之间的 if 语句?

oop - 理解对象交互的一些技巧是什么