mardi 27 août 2019

Inline lambdas in header files

This is similar to other questions I've seen, but given C++17's introduction of inline variables, it's worth asking. Consider this pattern:

auto to_ref = [](auto const& ptr) -> decltype(auto) { return *ptr; }

std::vector<std::unique_ptr<Foo>> foo_ptrs = from_somewhere();
for (Foo const& foo : foo_ptrs | transform(to_ref)) {
}

The to_ref generic lambda is...well, generic...so it makes sense to put it in a header so people aren't duplicating it everywhere.

My question: do the linkage considerations for templates also apply for generic lambdas? In other words, it is the responsibility of the compiler/linker to ensure that ODR is not violated for multiple instantiations of a given template with the same template arguments. Can I rely on that same behavior, or should I prepend the inline specifier to the auto to_ref = ...; specification?

Aucun commentaire:

Enregistrer un commentaire