Noman Javed
Noman Javed

Reputation: 51

Calling different functions depending on the template parameter c++

I want to have something like that

class A
{
public:
    Array& operator()()
    { . . . }
};

class B
{
public:
    Element& operator[](int i)
    { ... }
};

template<class T>
class execute
{
public:
    output_type = operator()(T& t)
    {
        if(T == A)
            Array out = T()();
        else
        {
            Array res;
            for(int i=0 ; i < length; ++i)
                a[i] = t[i];
        }
    }
};

There are two issues here:

  1. meta-function replacing if-else in the execute operator()
  2. return type of execute operator()

Upvotes: 4

Views: 236

Answers (2)

UncleZeiv
UncleZeiv

Reputation: 18488

Just specialize the template class.

template<class T>
class execute
{};

template<>
class execute<A>
{
 A operator()(A& t)
 {
   /* use A, return A */
 }
};

template<>
class execute<B>
{
 B operator()(B& t)
 {
   /* use B, return B */
 }
};

Upvotes: 3

sbi
sbi

Reputation: 224049

Just overload the operator:

// used for As
Array operator()(A& a)
{
  // ... 
}

// used for everything else
typename T::Element operator()(T& t)
{
  // ... 
}

If you just need A and B, the second could also be specific to B:

// used for Bs
B::Element operator()(B& b)
{
  // ... 
}

Upvotes: 2

Related Questions