Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do this with a template class in c++

Tags:

c++

templates

I have a class that is similar to this one:

int add(int a,int b)
{
    return a+b;
}
int sub(int a,int b)
{
    return a-b;
}
class C
{
    int m_functionType;
    C(int functionType)
    {
        m_functionType=functionType;
    }
    int calc(int a, int b)
    {
         switch(m_functionType)
         {
            case 1:  // add
               return add(a,b);
               break;
            case 2: // subtract
                return sub(a,b);
          }
     }
};

and the use it as follow:

main()
{ 
    C add(1);
    C sub(2);
    auto x=add.calc(1,2);
    auto z=sub.calc(2,1);
}

This code works, but the function which should be called is resolved at run time, I am looking for a solution that the solves the functions to call at compile time. something such as this:

template <int func>
class C
{
   int calc(int a, int b)
    {
         switch(func)
         {
            case 1:  // add
               return add(a,b);
               break;
            case 2: // subtract
                return sub(a,b);
          }
     }
};


 main()
{ 
    C<1> add;
    C<2> sub;
    auto x=add.calc(1,2);
    auto z=sub.calc(2,1);
}

Is the above code actually resolves the function during compile time or it still resolve it during run time?

Is there any way that I can do this using a template class? Assuming I want to compile it on Visual studio 2013 and GNU which they have some c++11 capability.

like image 367
mans Avatar asked Apr 23 '15 16:04

mans


1 Answers

In your example func is resolved at run-time in main:

C add(1);
C sub(2);

Compile-time would mean:

C<1> add;
C<2> sub;

If the change above is acceptable, C++98/03 classic idea is to use function overloads:

template <int v>
struct IntToType {
    enum {val = v};
};

int calc_impl(a, b, IntToType<1>) {
    return add(a, b);
}

int calc_impl(a, b, IntToType<2>) {
    return sub(a, b);
}

template <int func>
class C {
    int calc(int a, int b) {
        return calc_impl(a, b, IntToType<func>());
    }
};

Notes:

  1. calc_impl are just two functions taking three arguments. The name of the third argument is omitted because it is not used. They are overloaded by third parameter, because IntToType<1> and IntToType<2> are two different types.
  2. You can put calc_impl functions into private section of your class for better ergonomics.
like image 88
anxieux Avatar answered Oct 03 '22 13:10

anxieux