我面臨以下問題。假設我有兩個(或更多)這樣的列舉類:
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在代碼的命名空間中定義它們的事實。
您知道問題出在哪里嗎?您是否知道如何構建一個適用于該任務的函式?謝謝。
uj5u.com熱心網友回復:
一種選擇是撰寫幾個多載函式,每個函式處理不同的列舉型別。例如:
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
uj5u.com熱心網友回復:
我同意 273K 和 templatetypedef 關于使用多載的觀點。
但是,如果您決定在一個地方擁有一個包含案例處理邏輯的模板,您可以這樣做:
#include <iostream>
#include <type_traits>
using std::cout;
enum class CURSOR { ON, OFF };
enum class ANSI { ON, OFF };
template <typename T>
void OPTION(T opt) {
if constexpr (std::is_same_v<T, CURSOR>) {
if (opt == CURSOR::ON) cout << "cursor is on\n";
else if (opt == CURSOR::OFF) cout << "cursor is off\n";
} else if constexpr (std::is_same_v<T, ANSI>) {
if (opt == ANSI::ON) cout << "ANSI is on\n";
else if (opt == ANSI::OFF) cout << "ANSI is off\n";
}
}
int main() {
OPTION( CURSOR::ON );
OPTION( ANSI::ON );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495872.html
