禁止将rvalue引用传递给函数

Rom*_*man 10 c++ stl c++11

我们有以下便利功能,可以从地图中获取值,或者如果找不到键,则返回后备默认值.

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;
    }
Run Code Online (Sandbox Code Playgroud)

这个函数的问题是它允许传递一个临时对象作为第三个参数,这将是一个bug.例如:

const string& foo = FindWithDefault(my_map, "");
Run Code Online (Sandbox Code Playgroud)

是否可以通过使用std :: is_rvalue_reference和static assert以某种方式禁止将rvalue引用传递给第三个参数?

Obe*_*ron 11

添加这个额外的重载应该工作(未经测试):

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;
Run Code Online (Sandbox Code Playgroud)

重载决策将为rvalue引用选择此重载,并= 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!");
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

对于第二次调用,MSVC在此处给出以下错误foo:

rval.cpp(8) : error C2280: 'void foo(const char &&)' : attempting to reference a deleted function
        rval.cpp(2): See declaration of 'foo'
Run Code Online (Sandbox Code Playgroud)

然而,第一个调用工作正常,如果你注释掉第二个调用,那么程序就会编译.