【发布时间】:2011-10-13 00:20:31
【问题描述】:
以下是否会导致明确定义的行为?也就是说,如果您将非可变参数函数 f 转换为可变参数函数 g 并使用 f 期望的参数调用 g,那么行为是否与使用这些参数调用 f 的行为匹配?
class Base {};
class Derived1 : public Base {
public:
int getInt1() {return 1;}
};
class Derived2 : public Base {
public:
int getInt2() {return 2;}
};
typedef int (*vfunc)(...);
int foo (vfunc f) {
Derived1 d1;
Derived2 d2;
return f(&d1, &d2);
}
int bar (Derived1 * p1, Derived2 * p2) {
return p1->getInt1() + p2->getInt2();
}
int main (int argc, char ** argv) {
return foo((vfunc)bar); // Is this program guaranteed to return 3?
}
更新
有没有什么方法可以让程序得到很好的定义,即使使用专有关键字?比如做一些这里提到的__cdecl之类的东西:
http://msdn.microsoft.com/en-us/library/984x0h58%28v=vs.80%29.aspx
我的最终目标是有一个matcher 函数尝试匹配 X 指针列表。 matcher 函数接受一个谓词(不一定是一个函数......可能是一个列表)并接受一个函数,它将把匹配的结果传递给它。传递给它的回调函数采用与匹配的谓词相同的参数类型和数量。
【问题讨论】:
-
我相信并期望答案是这是未定义的行为。
-
当您说“专有关键字”时,您是什么意思?您的目标是什么编译器(以及版本和设置)?您是否愿意接受其他更好的解决方案(例如
std::function)? -
Visual Studio 中的
__cdecl之类的东西。我也愿意接受其他解决方案。