重载与原始函数不同的函数仅在参数列表中"const"

overloading a function which differs from the original only by "const" in parameter list

本文关键字:函数 参数 列表 const 原始 重载      更新时间:2023-10-16

我有一个关于重载一个只有"const"差异的函数的问题。例如,如果有一个函数 A,它是按引用传递的,则可以通过按引用传递到常量来重载它。但是,何时调用第一个,何时调用第二个?谢谢!

这绝对没问题。

void foo(int& ) { std::cout << "refn"; }
void foo(const int& ) { std::cout << "crefn"; }

如果您传递类型为 int 的非常量左值,则将调用第一个。第二个将在任何其他情况下调用。

int i = 4;
const int ci = i;
foo(4);  // cref
foo(i);  //  ref
foo(ci); // cref
foo(1L); // cref
struct X {
    operator int() { return 42; }
};
foo(X{}); // cref

我假设你的意思是这样的

void A(int& arg)
{
    ...
}
void A(const int& arg)
{
    ...
}

然后你可以使用这样的函数

int i = 5;
A(i);  // will call `A(int&)`
A(5);  // will call `A(const int&)`
const int ci = 5;
A(ci);  // will call `A(const int&)`