简体   繁体   中英

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?

to_ref is an object with a template operator() , it is not a template of any kind.

You will need to mark it inline to obey the ODR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM