2

I have a header only class with two functions

  //F1
  void add_argument(const std::string &name, const std::string &desc,
                    const bool required = false) {
    //...
  }

and

  //F2
  void add_argument(const std::string &name, const std::string &long_name,
                    const std::string &desc, const bool required = false) {
    //...
  }

and in my code I call

//L1: should call F2
add_argument("-w", "--write",
             "Writes the calibrated values to the config.",
             false);

//L2: should also call F2
add_argument(
  "-i", "--interval",
  "The time interval in milliseconds that it should check in.");

The intended behavior is that both L1 and L2 call the same method F2. However, when I compile and run, L1 does correctly call F2, but L2 calls F1.

What I'm wondering is why it appears that in L2 it is converting the last string to a boolean and not using the default argument? Is this a part of the C++11 standard, is it a compiler/linker bug, or am I making a dumb mistake?

This is being compiled and run on a RaspberryPi

  Linux raspberrypi 4.14.71-v7+ Raspbian GNU/Linux 9 (stretch)
  g++ (Raspbian 6.3.0-18+rpi1+deb9u1) 6.3.0 20170516
  GNU ld (GNU Binutils for Raspbian) 2.28

using a command similar to this (I'm actually using cmake with make to the commands are hard to copy exactly)

  g++ -std=c++11 -Wall -I. main.cpp -o test

(I get no compiler warnings)

Jesse Laning
  • 490
  • 4
  • 12
  • 4
    String literals are pointers, and the language rules say that pointer-to-bool conversion is preferred over user-defined conversions (i.e. `const char[]` to `std::string`). See [here](https://stackoverflow.com/questions/316181/why-does-the-compiler-choose-bool-over-string-for-implicit-typecast-of-l) for a detailed explanation – alter_igel Dec 10 '18 at 19:33
  • You can try explicitly constructing a `std::string`, for example by passing `std::string("The time interval in milliseconds that it should check in.")`. But I'm not sure if there's a simpler solution that prevents this pitfall from happening silently in the first place – alter_igel Dec 10 '18 at 19:35
  • 2
    With C++17 string literals can be used: `"string"s`. See: https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s – Evg Dec 10 '18 at 19:36
  • Thanks for the help, the duplicate answers solved it. – Jesse Laning Dec 10 '18 at 19:41

0 Answers0