我可以获得一个内联的功能表吗?

时间:2017-06-29 13:37:40

标签: c++ function-pointers inline

考虑以下示例:

#include <iostream>
#include <type_traits>

inline void f()
{
    std :: cout << "Welcome to f!" << std :: endl;
}

inline void g()
{
    std :: cout << "Welcome to g!" << std :: endl;
}

inline void h()
{
    std :: cout << "Welcome to h!" << std :: endl;
}

typedef void (*function)();
const function table[] = {f, g, h};

int main()
{
    int idx;
    std :: cin >> idx;
    table[idx]();
}

这里我有三个功能,fgh。我将他们的指针放入const数组。然后,在运行时,我要求我的用户提供一个数字,并调用表中相应的函数。

我想这不会被内联,我是否正确?我试图检查汇编代码,但我真的很厌烦阅读汇编。

所以我想知道,我有更好的选择来接听内联fgh的来电吗?我的意思是,如果我只是做一个转换,这将完美无缺。

注意:这只是一个示例,在实际场景中,我将拥有一组函数,这些函数在编译时已知,但由有点冗长的过程决定。所以我不能仅仅例如在switch语句中编写代码。

1 个答案:

答案 0 :(得分:0)

如果使用正确的const表达式,则可以保证代码在编译时内联。看看这个帖子中的条件:When does a constexpr function get evaluated at compile time?