简体   繁体   中英

C++ Variadic parameters with out first one

it's any possibility to use a variadic parameters with out specification of first one?

For example:

This code is perfectly fine:

void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}

But I would like to have the something function in this way:

void something(const char*...)

It's any possibility to do something like that? and after that to access the members? if yes, how?

Thanks

Here is how you would use a C++ variadic template. You can call something() with any even number of const char* arguments eg something("k1", "v1", "k2", "v2") . It will build a map<string,string> from these arguments by recursively calling the buildMap() function, and then call useMap() to do whatever actual work you want done with the map.

void buildMap(std::map<std::string, std::string>& data) 
{
}

template<typename... Args>
void buildMap(
    std::map<std::string, std::string>& data, 
    const char* layout, 
    const char* button, 
    Args... args) 
{
    data.insert(std::make_pair(layout, button));
    buildMap(data, args...);
}


void useMap(std::map<std::string, std::string>& data) 
{
    // TODO: do something here
}

template<typename... Args>
void something(Args... args) {
    std::map<std::string, std::string> data;
    buildMap(data, args...);
    useMap(data);
}

As state in comment std::initializer_list seems to do the job

void something(std::initializer_list<std::pair<std::string, std::string>> layoutAndButtons)
{
    // std::map<std::string, std::string> m(layoutAndButtons); // potentially
    for (auto const& p : layoutAndButtons) {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

or even, if you really need a map:

void something(const std::map<std::string, std::string>& layoutAndButtons)
    for (auto const& p : layoutAndButtons) {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

With usage similar to:

something({{"Some", "things"}, {"are", "done"}});

If you really want variadic template, I suggest:

template<typename... Args>
void something(Args... args) 
{
    static_assert(sizeof...(Args) % 2 == 0, "wrong number of argument");
    const char* layoutAndButtons[] = {args...};

    std::map<std::string, std::string> m;
    for (auto it = std::begin(layoutAndButtons);
         it != std::end(layoutAndButtons);
         it += 2) {
        auto layout = *it;
        auto button = *(it + 1);
        m.emplace(layout, button);
    }
    for (auto const& p : m)
    {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

If you can use C++14 ( std::index_sequence and std::make_index_sequence ) you can avoid recursion wrapping your args... in a std::tuple , generating a list of indexes and initializing the std::map with indexes and std::get() .

I mean: if you write an helper function as follows

template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }

in something() you can initialize data as follows

auto data = getMap(std::tie(args...),
                   std::make_index_sequence<(sizeof...(Args)>>1)>{});

but I also suggest to precede this line with a static_assert() to check that the number of args... is even; something like

static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!"); 

The following is a full working example

#include <map>
#include <tuple>
#include <iostream>
#include <type_traits>

template <typename ... Args, std::size_t ... Is>
std::map<std::string, std::string> getMap
   (std::tuple<Args...> const & t, std::index_sequence<Is...> const &)
 { return { {std::get<(Is<<1)>(t), std::get<(Is<<1)+1U>(t)} ... }; }

template <typename... Args>
void something (Args... args)
 {
   static_assert( (sizeof...(Args) & 1U) == 0U, "#Args is odd!");

   auto data = getMap(std::tie(args...),
                      std::make_index_sequence<(sizeof...(Args)>>1)>{});

   for ( auto const & p : data )
      std::cout << '[' << p.first << ',' << p.second << ']';

   std::cout << std::endl;
 }

int main ()
 {
   something("k1", "v1", "k2", "v2", "k3", "v3"); // compile
   //something("k1", "v1", "k2", "v2", "odd!"); // static_assert() failure
 }

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