C++ 我是否可以执行一个";可变语句“;在一个函数内和没有定义?
我面临的问题是,如果不定义或产生性能影响,我就看不出它是如何解决的,尽管我确信有人可以为我指出解决方案 我有一个算法,可以产生一系列(大的)值。为了简单起见,在下面我假设它是For循环中的For循环,尽管在我的代码中它比这更复杂 在循环的核心,我需要对生成的值进行计算。虽然这些值的算法保持不变,但计算结果有所不同 所以基本上,我得到的是:C++ 我是否可以执行一个";可变语句“;在一个函数内和没有定义?,c++,c-preprocessor,virtual-functions,C++,C Preprocessor,Virtual Functions,我面临的问题是,如果不定义或产生性能影响,我就看不出它是如何解决的,尽管我确信有人可以为我指出解决方案 我有一个算法,可以产生一系列(大的)值。为了简单起见,在下面我假设它是For循环中的For循环,尽管在我的代码中它比这更复杂 在循环的核心,我需要对生成的值进行计算。虽然这些值的算法保持不变,但计算结果有所不同 所以基本上,我得到的是: void normal() { // "Algorithm" producing numbers (x and y): for (int x
void normal() {
// "Algorithm" producing numbers (x and y):
for (int x=0 ; x<1000 ; x++) {
for (int y=0 ; y<1000 ; y++) {
// Calculation with numbers being produced:
if ( x+y == 800 && y > 790) {
std::cout << x << ", " << y << std::endl;
}
// end of calculation
}}
}
并从中派生一个“可调用”类:
class inner : public inner_0 {
public:
virtual void call(int x, int y) {
if ( x+y == 800 && y > 790) {
std::cout << x << ", " << y << std::endl;
}
}
};
类内部:公共内部\u 0{
公众:
虚拟无效调用(整数x,整数y){
如果(x+y==800&&y>790){
std::cout函子:
struct Caller
{
void operator()(int x, int y)
{
if ( x+y == 800 && y > 790)
std::cout << x << ", " << y << std::endl;
}
};
template <typename T>
void your_algorithm(T foo)
{
for (int x=0 ; x<1000 ; x++)
for (int y=0 ; y<1000 ; y++)
foo(x, y);
}
int main()
{
your_algorithm(Caller());
}
struct调用者
{
void运算符()(整数x,整数y)
{
如果(x+y==800&&y>790)
std::cout函子:
struct Caller
{
void operator()(int x, int y)
{
if ( x+y == 800 && y > 790)
std::cout << x << ", " << y << std::endl;
}
};
template <typename T>
void your_algorithm(T foo)
{
for (int x=0 ; x<1000 ; x++)
for (int y=0 ; y<1000 ; y++)
foo(x, y);
}
int main()
{
your_algorithm(Caller());
}
struct调用者
{
void运算符()(整数x,整数y)
{
如果(x+y==800&&y>790)
std::cout为什么不将整个函数作为模板,并传入函数对象:
template <type T> workOnGeneratedNumbers(T functor){
// "Algorithm" producing numbers (x and y):
for (int x=0 ; x<1000 ; x++) {
for (int y=0 ; y<1000 ; y++) {
// Calculation with numbers being produced:
functor(x,y);
// end of calculation
}
}
}
模板工作生成数(T函子){
//产生数字(x和y)的“算法”:
对于(int x=0;x为什么不将整个函数作为模板,并传入函数对象:
template <type T> workOnGeneratedNumbers(T functor){
// "Algorithm" producing numbers (x and y):
for (int x=0 ; x<1000 ; x++) {
for (int y=0 ; y<1000 ; y++) {
// Calculation with numbers being produced:
functor(x,y);
// end of calculation
}
}
}
模板工作生成数(T函子){
//产生数字(x和y)的“算法”:
对于(int x=0;xIf您的编译器支持C++0x,lambda也很酷。:)如果您的编译器支持C++0x,lambda也很酷。:)
struct Caller
{
void operator()(int x, int y)
{
if ( x+y == 800 && y > 790)
std::cout << x << ", " << y << std::endl;
}
};
template <typename T>
void your_algorithm(T foo)
{
for (int x=0 ; x<1000 ; x++)
for (int y=0 ; y<1000 ; y++)
foo(x, y);
}
int main()
{
your_algorithm(Caller());
}
template <type T> workOnGeneratedNumbers(T functor){
// "Algorithm" producing numbers (x and y):
for (int x=0 ; x<1000 ; x++) {
for (int y=0 ; y<1000 ; y++) {
// Calculation with numbers being produced:
functor(x,y);
// end of calculation
}
}
}