Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ from macros to templates

I'm trying to change some macros (we have a bunch of them) for function templates. Many times, I have the following scenario:

#include <iostream>

void function_A( void )
{
    std::cout << "function A" << std::endl;
}

void function_B( void )
{
    std::cout << "function B" << std::endl;
}

#define FOO( _bar ) \
do { \
    /* ... do something */ \
    function_##_bar(); \
    /* ... do something */ \
} while( 0 )

int main() 
{
    FOO( A );
    FOO( B );
}

How can I express FOO as a function template and achieve the same result?

I am thinking in something like:

template < ??? _bar >
void foo()
{
   // somehow link function_X and _bar
}

Performance is a must!!

Thanks in advance.

like image 584
Albert Avatar asked Nov 25 '25 18:11

Albert


2 Answers

You could use a case statement as in Zenith's answer, but you can do it at compile-time with templates like this:

enum class FunctionOverload
{
    A, B
};

template <FunctionOverload T>
void function();

template<>
void function<FunctionOverload::A>()
{
    std::cout << "function A" << std::endl;
}

template<>
void function<FunctionOverload::B>()
{
    std::cout << "function B" << std::endl;
}

template <FunctionOverload T>
void foo()
{
    //do stuff
    function<T>();
    //do more stuff
}

int main() 
{
    foo<FunctionOverload::A>();
    foo<FunctionOverload::B>();
}
like image 50
TartanLlama Avatar answered Nov 27 '25 10:11

TartanLlama


You actually can't do string pasting like that with templates. There may be a better way to solve your real problem, but the most straightforward way I can think of to solve your stated question is to pass the address of the function to the template (this has the further advantage that you aren't limited to functions, you can pass anything that can be called with no parameters):

template <typename Callable>
void foo(Callable func)
{
    // Stuff
    func();
}

int main() 
{
    foo(&function_a);
    foo(&function_b);
}
like image 32
Mark B Avatar answered Nov 27 '25 09:11

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!