【发布时间】:2009-05-30 18:50:04
【问题描述】:
我想编写两个不同的函数来处理一个常量值和一个给定类型的变量(即int)。
这里是示例测试用例:
int main(void) {
int x=12;
F(5); // this should print "constant"
F(x); // this should print "variable"
}
我认为定义就足够了:
void F(int v) { cout << "constant\n"; }
void F(int& v) { cout << "variable\n"; }
这假定编译器将选择int& 变量作为“更好的专业化”和int 常量作为唯一选择)。但是,G++ 结果是这样的:
test.cc: In function ‘int main()’:
test.cc:13: error: call of overloaded ‘F(int&)’ is ambiguous // for line: F(x);
test.cc:4: note: candidates are: void F(int)
test.cc:5: note: void F(int&)
G++ 确实为常量选择了F(int),但不知道为变量选择哪个函数。
有谁知道为什么会这样?
背景:我正在 C++ 中尝试类似 prolog 的统一方法。在 functor(x,5) <=> functor(3,5) 等情况下,能够知道常量和变量之间的区别将有助于我选择所需的统一行为(赋值或比较)。
【问题讨论】:
标签: c++