views:

81

answers:

2

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()

Thanks in anticipation,

Noman

+2  A: 

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 */
 }
};
UncleZeiv
Your template spec syntax is a little off. Shouldn't it be template<> class execute<B>?
DeadMG
@UncleZeiv: @DeadMG is right, I went in to fix that. Hope you don't mind.
sbi
oops, thanks DeadMG and sbi for fixing!
UncleZeiv
Oh, and it might be better to not to define the base template at all.
sbi
I normally put a false static assert in.
DeadMG
+3  A: 

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)
{
  // ... 
}
sbi