Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
MaestroGlanz Avatar asked Sep 03 '16 12:09

MaestroGlanz


People also ask

Can we define function before main in C?

More than one function called before main should be defined in the reverse order of required execution. Just to make sure we don't end up with syntactical errors these functions should not return or receive any value.

Can we define function without declaration in C?

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Can you call a function before it has been defined C?

In C, if a function is called before its declaration, the compiler assumes the return type of the function as int. For example, the following program fails in the compilation.


1 Answers

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", it will select the proper namespace for that specific function in accordance with the standard version:

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

// ... somewhere
to_string(/*...*/);  // it should use the proper namespace
like image 151
BiagioF Avatar answered Sep 30 '22 11:09

BiagioF