禁止传递对函数的右值引用
disallow passing of rvalue reference to a function
我们有以下方便函数,可以从映射中获取值或者如果找不到密钥,则返回回退默认值。
template <class Collection> const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return value;
}
return it->second;
}
此函数的问题在于,它允许将临时对象作为第三个参数传递,这将是一个错误。例如:
const string& foo = FindWithDefault(my_map, "");
是否可以通过使用std::is_rvalue_reference和静态断言?
添加这个额外的过载应该有效(未经测试):
template <class Collection>
const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type&& value) = delete;
重载解析将为右值引用选择此重载,并且= delete
使其成为编译时错误。或者,如果你想指定一个自定义消息,你可以选择
template <class Collection>
const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type&& value) {
static_assert(
!std::is_same<Collection, Collection>::value, // always false
"No rvalue references allowed!");
}
std::is_same
用于使static_assert
依赖于模板参数,否则即使不调用重载,也会导致编译错误。
编辑:这里是一个最小的完整示例:
void foo(char const&) { };
void foo(char const&&) = delete;
int main()
{
char c = 'c';
foo(c); // OK
foo('x'); // Compiler error
}
MSVC在此处对foo
的第二次调用给出以下错误:
rval.cpp(8) : error C2280: 'void foo(const char &&)' : attempting to reference a deleted function
rval.cpp(2): See declaration of 'foo'
然而,第一个调用运行良好,如果您注释掉第二个调用,则程序将编译。
相关文章:
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 无法将右值引用函数与 GCC 匹配
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 通过引用函数传递指针参数是什么意思?
- 常量引用函数参数的地址何时唯一?
- 我想了解为什么在这个例子中使用引用函数?或者引用在c++函数中的重要性
- C++ 通过引用函数传递数组,但内容保持不变
- 用数组或指针引用函数?
- 引用函数如何"int &foo();"工作?
- 常量引用函数参数:是否可以禁止临时对象?
- 计算在代码中引用函数的次数
- <initializer_list> 引用函数
- 字符串引用(函数)的差异
- 在类中引用函数时的"No Matching Function for Call"
- 无法通过引用函数"calcValues"中"firstNum"和"secondNum"变量来更改值
- 尝试引用已删除的函数(不引用函数)
- 引用函数指针
- 引用函数按值和自动返回
- 为什么我们可以取消引用函数指针
- 通过引用函数传递值的目的是什么