Tuesday, July 1, 2014

Determining whether if a function (or variable, or constant) is declared in C++11

As @mattn_jp pointed out on his blog entry, C/C++ allow use of redundant parenthesis in variable declaration. For example, both of the following statements conform to the language specification.

int i = 3; // declares variable i, initialized to 3
int (j) = 4; // declares variable j, initialized to 4

By using this feature, it is possible to create a macro that tests the existence of whatever variable or constant.

The macro: is_defined in the following example is one such implementation.

Compiling and running the code would likely emit is NAN defined? yes. But if you remove #include <cmath> the output will likely change to false, since NAN is a constant defined in cmath.

#include <iostream>
#include <cmath>

struct is_defined_t {
  static bool defined_;
  is_defined_t() { defined_ = false; }
  template <typename T> explicit is_defined_t(const T&) { defined_ = true; }
};

bool is_defined_t::defined_;

#define is_defined(arg) (([]() { is_defined_t(arg); return is_defined_t::defined_; })())

int main(int argc, char **argv)
{
  std::cout << "is NAN defined? " << (is_defined(NAN) ? "yes" : "no") << std::endl;
  return 0;
}

No comments:

Post a Comment