简体   繁体   中英

How to accept both std::vector and std::initializer_list

I have

void f(std::initializer_list<int> x);
// .cpp
void f(std::initializer_list<int> x) { /* Lots of code */ }

At some moment I need also

inline void f(std::vector<int> x) { /* I want call f(initializer_list), but cant */; }

My solution

void f_inner(const int* x, std::size_t size);
inline void f(std::initializer_list<int> x) { f_inner(x.begin(), x.size(); } 
inline void f(std::vector<int> x) { f_inner(x.data(), x.size()); }
// .cpp
void f_inner(const int* x, std::size_t size) { /* Lots of code */ }

Maybe there's a more elegant solution? But I don't want to move f_inner to .h and make it a template

Use a type like gsl span.

Both vector and initializer lists are contiguous containers, and a span to const data can wrap either at zero cost.

So you can throw one together that solves your problem cleanly. GSL span itself blocks it out of a misguided attempt to defend itself against dangling local spans constructed with ils.

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