Michael IV
Michael IV

Reputation: 11436

Template class Member function specialization

Before someone has marked this question as duplicate of this ,please let me explain my problem. I have a class template with member functions which are not templates.I want to have additional version of the body of such functions for a specific class template param.In my case it can be only two variations: "true" or "false"

Example:

  template <bool IsEven>
  class EvenOddProcessor{

      public:

          bool ProcessEvenOdd();

  };
   //Default definition:
  template<bool IsEven>    
  inline bool EvenOddProcessor<IsEven>::ProcessEvenOdd()
  {

        return false;

  }

  //Now I want to define the special case of the function
  //when the class template param is true:    
  inline bool EvenOddProcessor<true>::ProcessEvenOdd()
  {

        return true;

  }

Now,this works with MSVC compilers and doesn't with GCC.This is unsurprising because GCC is always more strict about C++ standard,which as far as I understand,doesn't allow member function specialization.However based on the answers to this question what I am trying to do still should be possible with some template magic.None of the solutions in that answers worked in my case.

Upvotes: 0

Views: 70

Answers (1)

You just need to mark it as a specialisation with template <>:

template <>
inline bool EvenOddProcessor<true>::ProcessEvenOdd()
{
    return true;
}

[Live example]

Upvotes: 2

Related Questions