简体   繁体   English

c ++从宏到模板

[英]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? 如何将FOO表示为功能模板并获得相同的结果?

I am thinking in something like: 我想的是:

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

Performance is a must!! 性能是必须的!!

Thanks in advance. 提前致谢。

You could use a case statement as in Zenith's answer, but you can do it at compile-time with templates like this: 您可以在Zenith的答案中使用case语句,但是您可以在编译时使用以下模板执行此操作:

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

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);
}

I don't think you need a function template for that. 我不认为你需要一个功能模板。 Here's one solution: 这是一个解决方案:

enum foo { A, B };

void CallFunction(foo f)
{
    switch(f)
    {
        case A: function_A(); break;
        case B: function_B(); break;
    }
}
...
int main()
{
    CallFunction(A);
    CallFunction(B);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM