重载与原始函数不同的函数仅在参数列表中"const"
overloading a function which differs from the original only by "const" in parameter list
我有一个关于重载一个只有"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&)`
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数