Question

I am a complete noob to meta-programming and my question is really simple,but I haven't found a simple answer.Something similar is answered here but I couldn't translate it to my needs.

I have a class like this

class Program {

 public:

   Program(){}

   SetMatrixUniform(){

      CallSomeMethodX();

   }

    ~Program(){}

};

But I have scenarios where I need the same class with the same methods but calling different functions in their bodies.Something like this:

 class Program {

 public:

   Program(){}

   SetMatrixUniform(){

      CallSomeMethodY();

   }

    ~Program(){}

};

I would like to have template interface to such a class with "true" parameter to select what to put into class member methods in compile time,instead of maintaining 2 such classes.

something like this:

  Program<true> myProg;   ///expands    CallSomeMethodX(); into  SetMatrixUniform()

while :

  Program<false> myProg;   ///expands    CallSomeMethodY(); into  SetMatrixUniform()

I have seen examples where class variations are declared and then through specialization the final class extends one of those.I would like to do it without using inheritance as the performance is really important here.

Was it helpful?

Solution

This can be solve using template specialization

We first declare Programm as a template taking a bool parameter:

template<bool B>
struct Programm
{
    struct SetMatrixUniform()
    {
         std::cout << "General / Generic Implementation" << std::endl;
    }
};

Now we can provide another implementation/specialization for a more concrete case, e.g if B == true

template<>
struct Programm<true>
{
    void SetMatrixUniform()
    {
       std::cout << "Sepcific Implementation For B == true" << std::endl;
    }
};

As bool can only hold two states: true and false, the first implementation will be used if the template is instantiated with false and the second if the template is instantied with true.


This solution however is kind of verbose and requires you two reimplement much of your functionality. If you simply need different behaviour in just some methods, you can also directly compare B. E.g:

template<bool B>
struct Programm
{
    void SetMatrixUniform()
    {
        if(B == true)
            //...
        else
            //...
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top