My primary function is about 1000 lines long. But I have to create two configurations : Debug & Release version. In general they are the same but they also have many differences. My source file becomes very long and each time I have to update, it's hard to update quickly both two configurations.
Are there any methods to wrap these configurations into a single function? That makes my code easier to work then. I don't want to use if because it directly affects my program's performance.
@ Fransje
Thanks for your reply. But it causes an another problem : It only produces a function, "Debug", or "Release". I want two functions with two different configurations, but my code should be clear as possible. For example, a normal function, but when compiling it can produce multiple functions with multiple different configurations, is it possible?
I want to keep my code as short & clear as possible.
In your example, you only specify the "debug" or "release" case, but I need both. That's why I need a generic function but it's still able to create multiple functions with multiple different configurations (for example it will create two functions (Debug and Release versions)).
#include <iostream>
#include <vector>
#include <cassert>
#include <type_traits>
struct release
{
staticvoid foo() { std::cout << "foo for release build\n" ; }
template< typename T > using vector = std::vector<T> ;
// more release build specific stuff
// ...
};
struct debug
{
staticvoid foo() { std::cout << "foo for debug build\n" ; }
template< typename T > struct vector : std::vector<T>
{
using base = std::vector<T> ;
using base::base ; // requires support for inherited constructors
// clang 3.3 GCC 4.8
usingtypename base::size_type ;
// ...
T& operator[] ( size_type pos )
{
validate_pos(pos) ;
returnthis->at(pos) ;
}
const T& operator[] ( size_type pos ) const
{
validate_pos(pos) ;
returnthis->at(pos) ;
}
void validate_pos( size_type pos ) const
{
if( pos >= this->size() ) std::clog << "vector: out of range access\n" ;
assert( pos < this->size() && "vector: out of range access" ) ;
}
};
// more debug build specific stuff
// ...
};
template < bool DEBUG = false > void my_common_function()
{
using config = typename std::conditional< DEBUG, debug, release >::type ;
typename config::template vector<int> vec { 1, 2, 3, 4, 5 } ;
std::size_t pos = 10 ;
int value = 5 ;
// ...
config::foo() ;
// ...
vec[pos] = value ;
// ...
}
int main()
{
std::cout << "call release version of my_common_function\n\n" ;
my_common_function<>() ; // release version
std::cout << "\ndone\n\n" ;
std::cout << "call debug version of my_common_function\n\n" ;
my_common_function<true>() ; // debug version
std::cout << "\ndone\n" ;
}
call release version of my_common_function
foo for release build
done
call debug version of my_common_function
foo for debug build
vector: out of range access
Assertion failed: pos < this->size() && "vector: out of range access", ...