简体   繁体   中英

How to specify a member function (inside class is better) by the argument of class template?

I have some class like

enum Type {ONE, TWO};

template <enum Type T>
class A {
    void foo() {}
};

I want to specify the function foo() according to the template argument T of the class. Is it possible to be done inside the class ? Or, how to do it outside the class?

Edit:

what if my class is

template <class U, enum Type T>
class A {
    void foo() {}
};

This class cannot be simply specialized by giving two version of foo I found a solution at What is wrong with partial template specialization? which may turn out to make the code very long.

Is there any other solution to this, or should some other design be used ?

You can explicitly specialize members functions of class templates. You simply do:

template <>
void A<ONE>::foo()
{
//ONE stuff
}

Alternatively, you can use tag-dispatching. In this particular instance, they don't make much sense, but they might if your requirements are slightly different.

template <enum Type T>
class A
{
public:
  void foo() {fooImpl(std::conditional_t<T==ONE, std::true_type, std::false_type>());}

  void fooImpl(std::true_type)
  {
    cout << "ONE" << endl; 
  }

  void fooImpl(std::false_type)
  {
    cout << "TWO" << endl; 
  }
};

With the above definition,

int main()
{
  A<ONE>().foo();
  A<TWO>().foo();
  return 0;
}

prints

ONE
TWO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM