禁止传递对函数的右值引用

disallow passing of rvalue reference to a function

本文关键字:引用 函数 禁止      更新时间:2023-10-16

我们有以下方便函数,可以从映射中获取值或者如果找不到密钥,则返回回退默认值。

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'

然而,第一个调用运行良好,如果您注释掉第二个调用,则程序将编译。