_Bool_type

_Bool_typeが気になったので少し調査。

#include <iostream>

using namespace std;

class TrueFalse {
  bool r_;

public:
  TrueFalse(bool r) : r_(r) {};

  operator std::_Bool_type() const {
    return r_ ? _CONVERTIBLE_TO_TRUE : 0;
  }
};

void print_bool(TrueFalse& tf) {
  cout << (tf ? "true" : "false") << endl;
}

int main() {
  TrueFalse t(true);
  TrueFalse f(false);

  print_bool(t);
  print_bool(f);

  return 0;
}

VCではコンパイルできるけど、gccではできず。やっぱりVC独自か…


~/work$ g++ foo.cpp
foo.cpp:11: error: `std::_Bool_type' has not been declared
foo.cpp: In function `void print_bool(TrueFalse&)':
foo.cpp:17: error: could not convert `tf' to `bool'
~/work$ g++-4 foo.cpp
foo.cpp:11: error: expected type-specifier
foo.cpp: In function 'void print_bool(TrueFalse&)':
foo.cpp:17: error: could not convert 'tf' to 'bool'

でも、こっちはコンパイルできた。

#include <iostream>

using namespace std;

class TrueFalse {
  bool r_;

public:
  TrueFalse(bool r) : r_(r) {};

  operator bool() const {
    return r_;
  }
};

void print_bool(TrueFalse& tf) {
  cout << (tf ? "true" : "false") << endl;
}

int main() {
  TrueFalse t(true);
  TrueFalse f(false);

  print_bool(t);
  print_bool(f);

  return 0;
}


~/work$ g++ foo.cpp
~/work$ ./a.exe
true
false
これは正しいのかな?

追記
VCでもコンパイルできた。