MaestroGlanz MaestroGlanz - 3 months ago 12
C++ Question

Define function / method if not defined before c++

I don't use C++11 yet, so I wrote the functions

to_string(whatever)
by myself. They should only be compiled if they don't exist. If I switch to C++11, they should be skipped. I have something like this:

#ifndef to_string

string to_string(int a){
string ret;
stringstream b;
b << a;
b >> ret;
return ret;
}

string to_string(double a){
string ret;
stringstream b;
b << a;
b >> ret;
return ret;
}

#endif


This doesn't work apparently. Is something like this possible and if yes, how?

Answer

This is one of main purpose of namespace existence.

My suggest is to include your personal function in a proper namespace, something like:

namespace myns {
  std::string to_string(...) {
    // ...
  }
  // etc...
}

This is fundamental in order to avoid future conflict problems.

Afterwards, when you're going to use that function, you can simple select the proper function with a MACRO substitution.

Something like:

#if (__cplusplus >= 201103L) 
  #define my_tostring(X) std::to_string(X)
#else
  #define my_tostring(X) myns::to_string(X)
#endif

Note __cplusplus is a pre-defined macro which contains compiling information about standard version.


Edit:
Something less violent, as you prefer:

#if (__cplusplus >= 201103L) 
  using std::to_string;
#else
  using myns::to_string;
#endif

// ... somewhere
to_string(/*...*/);  // it should use the proper namespace
Comments