1

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 ?

Community
  • 1
  • 1
Kozuki
  • 97
  • 8

1 Answers1

2

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
Pradhan
  • 16,391
  • 3
  • 44
  • 59
  • ur solution needs to be written outside of the class. Is there any solution inside the class `A`? – Kozuki Jan 25 '15 at 17:29
  • @Kozuki Why would that be helpful? Why template it at all if you are going to provide the implementations for all the cases in the one template definition? – Pradhan Jan 25 '15 at 17:31
  • I just have lots of other template arguments and don't want to copy them for every function like this. – Kozuki Jan 25 '15 at 17:37
  • what's a 'in-class options'? – Kozuki Jan 25 '15 at 17:38
  • I meant added code showing how to provide definitions inside the class. – Pradhan Jan 25 '15 at 17:39
  • VS2013 is giving an error for `enable_if` version: error C2535: member function already defined or declared – Kozuki Jan 25 '15 at 18:07
  • Sorry, my `enable_if` example was incorrect. Have tested the above with `clang -std=c++1y`. You need C++14 for the `conditional_t` alias. If you don't have it, see [here](http://en.cppreference.com/w/cpp/types/conditional). – Pradhan Jan 25 '15 at 18:18
  • what if I have another template argument in class `A`, please read my edit. – Kozuki Jan 27 '15 at 07:34