开发者

Calling different functions depending on the template parameter c++

I want to have something like that

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

class开发者_JS百科 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()


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 */
 }
};


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜