我有一些简单的功能
int f_0(int);
int f_1(int);
...
int f_n(int);
Run Code Online (Sandbox Code Playgroud)
然后我有一些for循环,我调用f_i(),这个循环中的条件不必相同
for (int i = 0; i < n; i++) {
...
if (condition) {
int myInt = f_i(); // this is not real implementation but shows the result
// I want to achieve
... //edit
}
...
}
Run Code Online (Sandbox Code Playgroud)
以下是我尝试实现此方法的方法:
指向功能的指针
typedef int (*Foo) (int);
Foo fptr[] = { f_0, f_1, ... , f_n };
这是一种优雅的方法,但在我的情况下,它比分解循环慢4.4.函数的常量指针产生类似的结果.
有没有更好的方法来实现这个?理想的解决方案是具有紧凑代码的解决方案,但编译器会分解循环并让计算最快.
我正在使用MSVC 2012并在发布模式下运行,并将优化设置为最大化速度.
编辑:
这是我的测试代码:
head.h
namespace c {
const int w = …Run Code Online (Sandbox Code Playgroud) 我有一个类在构造函数中完成所有工作(它在那里构造,运行一些计算,输出它们,然后它在构造函数中被破坏所有这些).
这是简化的代码:
#include <iostream>
class myInt {
public:
myInt(int init) : mInt(init) {}
int mInt;
};
class SinglePara {
public:
SinglePara(myInt first) : member(first.mInt) { std::cout << member << std::endl; this->~SinglePara(); }
int member;
};
class TwoPara {
public:
TwoPara(myInt first, myInt second) : member1(first.mInt), member2(second.mInt) { std::cout << member1 + member2 << std::endl; this->~TwoPara(); }
int member1, member2;
};
int main()
{
myInt one(1), two(2), three(3);
TwoPara myTwo(one, two); // outputs 3 as expected
TwoPara(one, two); // outputs 3 …Run Code Online (Sandbox Code Playgroud)