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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With