簡體   English   中英

是否有可能在編譯期間錯誤檢查case語句選項?

[英]Is it possible to error check case statement options during compile time?

如何以這樣的方式重寫此代碼:只要用戶通過有效方向,就會始終顯示正確的狀態(CA,AL等)字符串。

即如何確保編譯時枚舉方向中的每個enum_types都有一個有效的case語句,而不是運行時?

對於。 例如。 我故意評論了東方的案例陳述。 有沒有辦法在編譯時捕獲它。

我的直覺是(否)這就是語言提供默認情況的原因,因此這可能是不可能的。 但我會把它留給專家。

#include <iostream>
#include <string>

using namespace::std;

typedef enum 
{
    min_dir = -1,
    north,
    south,
    east,
    west,
}directions;

directions get_direction( string user_choice)
{
    if(user_choice == "north")
    {
        return north;
    }
    else if (user_choice == "south")
    {
        return south;   
    }
    else if (user_choice == "east")
    {
        return east;    
    }
    else if (user_choice == "west")
    {
        return west;    
    }
    else 
    {
        return min_dir;
    }
}

int main()
{
    string user_direction;
    cout << "Enter direction\n";
    cin >> user_direction;

    directions my_dir = get_direction(user_direction);
    cout << " Print direction's description\n";

    if( my_dir == min_dir)
    {
        // User passed junk
        return -1;
    }

    switch(my_dir)
    {
    case north:
        cout << "North - New york\n";break;
    case south:
        cout << "South - Alabama\n";break;
//  case east:
//      cout << "East - North Carolina\n";break;
    case west:
        cout << "West - California\n";break;
    default:
        cout << "Should Ideally never get here\n";break;
    }
    system("pause");
    return 0;
}

編輯:這只是一個例子來說明這一點。 這是代碼在工作。 他們在Windows(MSVC)和linux(gcc)中都編譯了這個。 這只是一個警告嗎? 我需要更嚴格的執法。

如果枚舉沒有case語句,我可以編寫一些在make過程中會出錯的代碼嗎?

在GCC(g ++)和Clang中,有-Wswitch-enum ,如果你沒有關於你要switchenum類型的可能值的case (即使你有一個default情況),它會發出警告。

在MSVC中,可比較的C4062來自警告級別3,但如果您有default語句,它不會警告您。 如果在這種情況下需要警告,則需要啟用級別4警告C4061 ,即使提供了默認情況,也會在缺少枚舉值時生成警告。

至於使其成為錯誤:所有編譯器都有“將警告視為錯誤”選項。 在GCC和Clang中,它是 - -Werror ; 在MSVC中,它是/WX

如果你使用一個對你的枚舉大小的子函數數組,並在聲明時初始化,那么你可以對數組的大小和枚舉數進行static_assert來驗證所有成員是否存在。 通過在數組中使用仿函數而不是函數指針,您還確定不會將nullptr作為值提供,因為將構造每個仿函數。

typedef enum 
{
    min_dir = -1,
    north = 0,
    south,
    count_dir
}directions;

class GoDir
{
public:
    virtual void operator()() {}
};

class GoNorth : public GoDir
{
public:
    virtual void operator()() {}
};

class GoSouth : public GoDir
{
public:
    virtual void operator()() {}
};

static GoDir actions[count_dir] = {GoNorth(), GoSouth()};
static_assert(sizeof(actions)/sizeof(actions[0]) == count_dir, "Error");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM