ISO/ IEC JTC1/SC22/WG21 N3509

Doc. no.: N3509
Date:     2013-01-10
Reply to: Olaf van der Spek <>
Title:    Operator Bool for Ranges

I. Introduction

This proposal adds explicit operator bool() to strings, containers and ranges.

II. Motivation and Scope

Bools can be true or false, integers can be zero or non-zero, (smart) pointers can be null or non-null and strings, containers and ranges can be empty or non-empty.
These states are being checked frequently, but only bools, integers and pointers can be checked directly. Strings, containers and ranges can't. Boost iterator_range can, though, which is very handy.
This proposal makes possible such direct checking by adding explicit operator bool() to all standard C++ strings, containers and ranges.

Direct checking is less verbose than using !empty() and allows code like the following where a definition is used inside a condition.

std::string f() { return "Olaf"; }

int main()
  if (std::string s = f())

  while (std::string s = f())

  // ugly, no type deduction possible
  for (std::string s; !(s = f()).empty(); )

III. Impact on the Standard

This is a pure extension and can be implemented using C++11 compilers and libraries.

IV. Technical Specifications

Add this function to all standard C++ strings, containers and ranges.

explicit operator bool() const { return !empty(); }

V. References˙