2015-11-05 16 views
2

我有一個命名空間中定義枚舉成員的一個長長的清單:檢查是否定義了枚舉成員?

namespace nsexp{ 
    enum expname{ 
    AMS1, 
    AMS2, 
    BESS1, 
    BESS2, 
    ... 
    }; 
} 

這是非常有用的,我不時地評論他們中的一些時間,這樣的事情:

namespace nsexp{ 
    enum expname{ 
    AMS1, 
    AMS2, 
    BESS1, 
    //BESS2, 
    ... 
    }; 
} 

使我可以將它們排除在我的程序之外。然而,這創造了一個功能,一些衝突,其中發生這種情況:

strcpy(filename[nsexp::BESS2],"bess/data_exp2"); 

我能解決也評論這條線,但如果我不包括許多成員這可累。有沒有辦法來檢查成員是否存在於命名空間中?

我在尋找類似:

if("BESS2 exists") strcpy(filename[nsexp::BESS2],"bess/data_exp2"); 
+0

這需要在編譯時做的,一個'如果()'語句不會幫助。我不確定一些模板元編程技巧是否可行,但即使如此,如果這樣做值得的話也值得懷疑。 –

回答

2

構建一個簡單的檢查對象,它可以讓你在運行時詢問殘疾人標誌的狀態。

#include <iostream> 

#define RUNTIME_CHECKS 1 

namespace nsexp{ 
    enum expname{ 
     AMS1, 
     AMS2, 
     BESS1, 
     BESS2, 
//  ... 
     NOF_EXPNAME 
    }; 


    class checker 
    { 
#if RUNTIME_CHECKS 
     struct impl 
     { 
      impl() { 
       std::fill(std::begin(disabled), std::end(disabled), false); 
      } 
      bool disabled[NOF_EXPNAME]; 
     }; 

     static impl& statics() { 
      static impl _; 
      return _; 
     } 

    public: 

     static void disable(expname e) { 
      statics().disabled[e] = true; 
     } 

     static bool disabled(expname e) 
     { 
      return statics().disabled[e]; 
     } 
#else 
    public: 
     static void disable(expname e) { 
      // nop - optimised away 
     } 

     static bool disabled(expname e) 
     { 
      // will be optimised away 
      return false; 
     } 
#endif 
    }; 
} 

using namespace std; 

auto main() -> int 
{ 
    nsexp::checker::disable(nsexp::AMS2); 
    nsexp::checker::disable(nsexp::BESS2); 

    cout << nsexp::checker::disabled(nsexp::AMS1) << endl; 
    cout << nsexp::checker::disabled(nsexp::AMS2) << endl; 
    cout << nsexp::checker::disabled(nsexp::BESS1) << endl; 
    cout << nsexp::checker::disabled(nsexp::BESS2) << endl; 

    return 0; 
} 

預期輸出:

0 
1 
0 
1 
+0

'auto'很好,但不是簡寫'int main()'? – SHR

+0

我有一個框架.cpp文件,我用它來編寫演示代碼。它恰好主要以這種方式定義。 –

0

有關定義,你可以分配給您枚舉常量預留值是什麼:

namespace nsexp{ 
    enum expname{ 
    AMS1 // = Undefined, 
    AMS2 // = Undefined, 
    BESS1= Undefined, 
    BESS2 // = Undefined, 
    ... 
    }; 
} 

if (BESS1 != Undefined) strcpy(filename[nsexp::BESS2],"bess/data_exp2"); 
+0

您定義'enum'的方式將導致由於錯誤/丟失逗號而導致的編譯錯誤。 – skypjack

+0

可以說'未定義'是-1。這將使'BESS2'等於未定義的+1,所以'AMS1'將等於'BESS2'。顯然不是你想要的。但無論如何,這是一個好主意。 – SHR

+0

@shr:對,你需要將標識符移動到列表的末尾:( –

0

可以稍微修改enum之前檢查值任何參考。

#include <iostream> 

enum expname { 
    // ENABLED 
    AMS1, 
    BESS1, 
    BESS2, 

    // DISABLED 
    DISABLED, 
    AMS2 
}; 

bool enabled(expname exp) { 

    return (exp < expname::DISABLED); 
} 

int main(const int argc, const char* argv[]) { 

    std::cout << enabled(expname::AMS1) ? "enabled" : "disabled" << std::endl; 
    std::cout << enabled(expname::AMS2) ? "enabled" : "disabled" << std::endl; 

    return 0; 
} 

此輸出

enabled 
disabled