lundi 5 novembre 2018

How can I prevent a const reference to bind to an rvalue?

I just spent too much time debugging something that I think could have been caught at compiletime, but no matter what I tried, I didn't get it to work.

The wrong code:

#include <string>
template<typename ContainerT>
std::pair<typename ContainerT::const_iterator, 
          typename ContainerT::const_iterator>
GetIterPair(const ContainerT& container) {
    return { container.cbegin(), container.cend() };
}

int main() {
    GetIterPair(std::string("hello"));
}

I tried lots of enable_if variants with !is_rvalue_reference<ContainerT> and is_lvalue_reference<...>, as a template argument and as a trailing return type, but couldn't get it to reject the rvalue.

Aucun commentaire:

Enregistrer un commentaire