1
class myclass {
  private:
    const myenum value;
  public:
    enum myenum { first, second }
    myclass(myenum value) : value(value) {}

    template < /* enable if myclass::value == myclass::myenum::first */ >
    void myfunc();
    template < /* enable if myclass::value == myclass::myenum::second */ >
    void myfunc();
}

int main(){
  myclass instance(myclass::myenum::first);
  instance.myfunc();
}

value is mode at witch myfunc() operates if you will. So far all my attempts have failed. Please tell whether it is possible to achieve the desired behavior and give me your suggestions

user3600124
  • 829
  • 1
  • 7
  • 19
  • Is [Using an enumeration as a template parameter](https://stackoverflow.com/questions/9116267/using-an-enumeration-as-a-template-parameter) helpful? – gsamaras Jul 19 '18 at 11:16
  • In my case enum template parameter is not given explicitly. `const myenum value` has to be used as a template parameter if it is even possible – user3600124 Jul 19 '18 at 11:20

2 Answers2

2

const myenum value; is a run-time value, which cannot be used to control the instantiation of myfunc at compile-time. If you want to do that, you need to pass myenum as a template parameter to myclass:

template <myenum value>
class myclass {
    // ...
};

Otherwise, you can use an if statement inside myfunc at run-time:

void myfunc()
{
    if(value == myenum::first) { /* ... */ }
    else { /* ... */ }    
}
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
1

The following is a way to keep the template feature only on the specific function and not the whole class. The price to pay to go from "run-time" class instance to "compile-time" function call is this mycall() function that contains this switch case statements.

#include <iostream>
enum myenum { first, second };
template <myenum E> void myfunc();
template <> void myfunc <first>(){
    std::cout << "First" << "\n";
}
template <> void myfunc <second>(){
    std::cout << "Second" << "\n";
}
class myclass {
private:
    myenum e;
public:
    myclass(myenum e): e(e){};
    void mycall() const{
        switch(e){
            case first:
                myfunc<first>();
                return;
            case second:
                myfunc<second>();
                return;
        }
    }
};
int main(){
    myenum e = first;
    myclass instance(e);
    instance.mycall();
}