Categories
Uncategorized

2021W38

I was on vacation. I caught cold, and it was not that great.

I peeked at work on Friday and caught an interesting C++ code review. Changing from this:

template <typename T>
class SomeClass {
  …
  template <typename U>
  Add(U&& item) {
    add(SomeClass(std::forward(item)));
  }
  …
}

To this:

template <typename T>
class SomeClass {
  …
  template <typename U>
  Add(U&& item) {
    add(SomeClass(std::forward<U>(item)));
  }
  …
}

It’s quite subtle, and easy to miss by accident. In this case T=std::string and U=std::string_view. The initial version has a compilation error in this case, “no matching function for call to ‘forward’”. Thankfully, clang also points out that it can’t infer the template, which is a big clue.

My read is that SomeClass(std::string) can be constructed from a std::string_view. But the compiler doesn’t know it has a std::string_view unless we correctly parameterize the call to std::forward.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s