c++ - Switch case statement with member variable in case -


i trying find way evaluate switch-case statement using member variable in case part. thought having global static variable below allowed const-expression.

unfortunately compiler tells me opposite:

error: ‘ll’ cannot appear in constant-expression error: ‘.’ cannot appear in constant-expression 

is there keyword or allow idea work? not expert of c++11, , heard constexpr.

enum myenum2 {a=0, b=1};  class test{     public:         operator myenum2 () { return val_;}         test(myenum2 val) :val_(val) {}         test() {}         static const myenum2 a;         static const myenum2 b;         myenum2 val_; };  const myenum2 test::a(myenum2::a); const myenum2 test::b(myenum2::b);  static const test ll;  int main() {     class test v = ll.a;     cout << v << endl;     switch(v) {         case ll.a:             cout << "a" << endl;             break;          case ll.b:             cout << "b" << endl;             break;     } } 

static elements parts of class , not of instance. have write:

case test::a: 

because value in case expression must constant expression, can use constexpr method this:

class {     public:         constexpr int x() { return 42; } };    int main() {     int i=42;     a;      switch (i)     {         case a.x():             ;      } } 

edit answer questions:

you can make constexpr object of class can instantiated constexpr needs constexpr constructor following:

#include <iostream>  using namespace std;  const int = 9;    // using const variable compile time const   class y             // using class containing const vals {     public:     int i;     constexpr y(int _i): i(_i){} };  constexpr y y(100);  int main() {     int var=9;      switch (var)     {         case i:             ;          case y.i:             ;     } } 

but can see not real use case kind of programming. switch statement can not "reused" other instance, because can not give switch expression other "object" of constants behave different. simple hide constant values in special way maybe not nice others read.

can give use case please?


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -