mercredi 24 août 2022

Strongly typed c++ varargs [duplicate]

I'm writing a utility function in c++ 11 that adds an element of a single type to a vector. Most variable argument docs/guides I've found show a template with the typedef type, but I'm looking to only allow a single type for all the variable arguments (const char*). The following is the relevant snippet of code:

Item.hpp:

// Guard removed
#include <vector>

class Item {
  public:
    Item(const char* n, bool (*optionChange)(uint8_t), const char*...);
  private:
    std::vector<const char*> options;
    void addOption(const char*);
}

Item.cpp:

#include "Item.hpp"

void Item::addOption(const char* option) {
  options.push_back(option);
}

Item::Item(
  const char* n, 
  bool (*optionChange)(uint8_t),
  const char* opts...
): name(n), type(MENU_TYPE_OPTS), selectedOpt(0) {
  addOption(opts...); // Doesn't compile
}

Compilation of the above code fails with the message error: expansion pattern 'opts' contains no argument packs.

Aucun commentaire:

Enregistrer un commentaire