空想犬猫記

※当日記では、犬も猫も空想も扱っておりません。(旧・エト記)

水曜日:C++関数の多重定義

かれこれC++で飯を食べさせていただいて10年くらいになるけれど、久々に血の気が弾いたあと鼻血がでるくらい酷いバグ入れてしまった。

幸い正式リリースモジュールを送信する数時間前に気付いて事無きを得たのだけど、本当に危なかった。

#include <iostream>
#include <string>

using namespace std;

void writeOption(const string& value)
{
  cout << "text: " << value << endl;
}

void writeOption(bool value)
{
  cout << "bool: " << (value ? "true" : "false") << endl;
}

int main()
{
  string s = "std::string de gonsu.";
  bool b = true;

  writeOption(s);
  writeOption(b);
  writeOption("text de gonsu");
  
  return 0;
}

最後の呼び出しがバグで、"test de gonsu" が出力されると思われがちだが、実際の結果は

text: std::string de gonsu.
bool: true
bool: true

となる。

とりあえずconst char*版を追加することで最小限の変更で修正をした。

同様の問題には ostream に対して wchar_t* の文字列を流し込んでポインタ値が出力されるバグなどがある。今のところ、この手の問題を未然に防ぐエレガントな方法が見つかっていない。