It seems that every project has a "utility" module with various code snippets used throughout other files and which doesn't fit any particular pattern.
What utility classes, functions, and macros do you find most useful in your C/C++ projects? Please keep the entries small (under 100 lines) and give only one example per post.
Get the number of elements in an array:
#define ITEMSOF(arr) (sizeof(arr) / sizeof(0[arr]))
(0[arr]
is identical to arr[0]
for arrays but will intentionally fail if it's used against a C++ object that overloads operator[]
.)
The C++ version is less intuitive but more type-safe:
template<int n>
struct char_array_wrapper{
char result[n];
};
template<typename T, int s>
char_array_wrapper<s> the_type_of_the_variable_is_not_an_array(const T (&array)[s]){
}
#define ITEMSOF(v) sizeof(the_type_of_the_variable_is_not_an_array(v).result)
Taken from this question [1] and Imperfect C++, by Matthew Wilson, section 14.3.
[1] http://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-functionsizeof
? - Potatoswatter
MAX_ITEMS
. Arrays of unknown size (such as pointers to allocated memory) aren't amenable to your method and need an accompanying size variable. - Edmund
size_t
, not int
, to store sizes. b) A more elegant (IMHO) C++ solution is template <typename T, size_t N> size_t array_size(const T (&arr)[N]) { return N; }
- Chris Lutz
MAX_ITEMS
, repeating it means that you might forget to update it if you change the array to use a different expression.) I also use ITEMSOF for code like static int static_data[] = {...}; for (size_t i = 0; i < ITEMSOF(static_data); i++) {...}
- Josh Kelley
#include <boost/...
scoped_ptr
and tribool
somehow end up including the entire Lambda or MPL components when bcp
'd. Not that I don't like Boost, but for this question... I'd downvote if I could. - Luis Machuca
bcp
dragging in a lot more components than you would expect. This has nothing to do with compiling. When you compile a program most modern C++ compilers are smart enough not instantiate templated code which is not actually used and linkers will not drag in object modules from libraries that are not actually referenced. This is more of a C++ feature than a Boost feature, although having well-designed modular code helps. - Ferruccio
This is useful for debugging:
#ifdef NDEBUG
#define Dprintf(format, ...)
#else
#define Dprintf(format, ...) \
fprintf(stderr, "[%s]:%s:%d: " format, __FILE__, \
__func__, __LINE__, ##__VA_ARGS__)
#endif
It uses variadic macros [1].
Edit: use NDEBUG which is standard.
[1] http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.htmlNDEBUG
, which is the standard macro used to determine whether we're in debug-mode or not? Also, it's bad practice to start names of user-defined macros with __
... - Christoph
NDEBUG
is only standard when running Visual Studio... - rubenvb
fprintf(stderr, "["__FILE__"]:%s:%d: "format, __func__, __LINE__, ##__VA_ARGS__)
and thus make the macro call slightly more efficient (you can do this because __FILE__
is a string literal provided by the preprocessor). - Trevor Boyd Smith
My own implementation of make_string() as proposed here [1] by Arkadiy [2]:
class make_string
{
public:
template <typename T>
make_string& operator<<( T const & datum )
{
buffer_ << datum;
return *this;
}
operator std::string () const
{
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
// usage:
void f( std::string const & );
int main()
{
std::string name = "David";
f( make_string() << "Hello " << name << "!" );
}
j_random_hacker suggests adding a const char* conversion to the class above so that it can be used with legacy/C libraries that take null terminated strings. I have had not that much time to think about it, but I feel unease as adding that conversion would allow the following code to compile [edit: bad example, read answer to second comment]:
const char* str = make_string() << "Hello world"; // 1
// ...
std::cout << str << std::endl; // 2
To the compiler the code above is correct, but the usage is wrong as in line 1 the make_string() temporary is destroyed and the pointer is no longer valid.
Response to second comment:
Assume a simple implementation of const char* operator:
class make_string
{
// ...
public:
operator const char* ()
{
return buffer_.str().c_str();
}
};
The str() creates a std::string object, whose scope is inside the operator const char_ method. The c_str() returns a pointer inside that std::string. By the time the caller receives the pointer, the std::string has gone out of scope and the memory has been released.
The other big difference with the code sample where the user requests the .c_str() from the std::string returned from the conversion operator is that the user is explicitly doing it and as such it appears in the code. If the conversion to null terminated string is implemented the user will have more trouble to detect where the error is.
void f( std::string const & );
void g( const char* );
f( make_string() << "Say hi" ); // works ok
g( make_string() << "Bye" ); // kills the application
g( (make_string() << "Hi again").c_str() ); // ok again std::string temporary is alive until g() returns
Now, try to explain what is so wrong with the second and not with the first or third lines one to the poor programmer whose application keeps dying. After all, she is just using a feature you are offering.
Another detail is that you could have a std::string member attribute and use it to force the lifespan of the std::string to be equivalent to that of the make_string object.
Anyway, I recomend everyone to read Modern C++ Design from Andrei Alexandrescu, and specially the chapter on smart pointers. The discussion of what features to implement is quite interesting. It changed my set of mind from 'implement as many features as you can' to a more conservative 'implement what is required, weight advantages and disadvantages of all other features'
[1] http://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet#469727char const* hi=string_maker << "Hello world"; char const* bye=string_maker << "Bye"; cout << hi;
. Guess its best to just say no. - community_owned
std::endl
, why not add it ? - smerlin
std::flush
will have no effect in a string stream). I have used some other manipulators (std::hex
and the like) to produce formatted output. It is just the 'function-style' manipulators that are not accepted. - David Rodríguez - dribeas
std::ostringstream
instead of forwarding operator<<
to a private member? That way, all manipulators work, and all other stream functions work the way users expect them to work, but you can overload the casting operators to work the way you want them to. Also, for a (non-const
) char *
overload, you could use strdup
(or something similar: char *stringdup(const std::string &s) { char *c = new char[s.size()]; memcpy(c, s.data()); return c; }
). - Chris Lutz
ostream
. It could use private inheritance (implemented in terms of), but you would need to add a using declaration... I guess that would be more concise than the code above, just did not think about it. - David Rodríguez - dribeas
strdup
, I don't think that is a good idea. The code is designed to be an in-place string builder. Adding that method would take that functionality away: the user would have to store the returned pointer in a variable and delete[]
it afterwards. The purpose of the class, when it was designed, was to be used as: foo( make_string() << "Hello, " << name );
the use is simple and the greatness of it is its simplicity of use. - David Rodríguez - dribeas
operator char *
to the string class. (Which is, of course, a bad idea.) - Chris Lutz
I use these pretty often, they are string trim functions.
inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
When calling a Win32 API that wants to write into a string buffer, it would be nice to be able to pass it a std::string or std::wstring directly.
Here's a simple way to enable that:
template <class C>
class _StringBuffer
{
typename std::basic_string<C> &m_str;
typename std::vector<C> m_buffer;
public:
_StringBuffer(std::basic_string<C> &str, size_t nSize)
: m_str(str), m_buffer(nSize + 1) { get()[nSize] = (C)0; }
~_StringBuffer()
{ commit(); }
C *get()
{ return &(m_buffer[0]); }
operator C *()
{ return get(); }
void commit()
{
if (m_buffer.size() != 0)
{
size_t l = std::char_traits<C>::length(get());
m_str.assign(get(), l);
m_buffer.resize(0);
}
}
void abort()
{ m_buffer.resize(0); }
};
template <class C>
inline _StringBuffer<C> StringBuffer(typename std::basic_string<C> &str, size_t nSize)
{ return _StringBuffer<C>(str, nSize); }
So now I can say:
std::string str;
GetWindowsDirectory(StringBuffer(str, MAX_PATH), MAX_PATH);
StringBuffer gives a writeable buffer to the API, and then on destruction it copies it into str
.
A simple hexdump
is often good to have...
#include <ctype.h>
#include <stdio.h>
void hexdump(void *ptr, int buflen) {
unsigned char *buf = (unsigned char*)ptr;
int i, j;
for (i=0; i<buflen; i+=16) {
printf("%06x: ", i);
for (j=0; j<16; j++)
if (i+j < buflen)
printf("%02x ", buf[i+j]);
else
printf(" ");
printf(" ");
for (j=0; j<16; j++)
if (i+j < buflen)
printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');
printf("\n");
}
}
This is Evil, I know, but it has come in handy:
#define private public
#include "OhSoEncapsulatedLittleObject.hpp" // Let me at'em!
#undef private
#define protected public
and #define class struct
- David X
#define ever ;;
Example use:
for(ever) { ... }
#define what(IGNORE) for(;;)
- Christoph
#define ty_two ;;) puts("DON'T PANIC"
so that you can do for(ty_two);
- Christoph
#define ever (;;)
. Everything is cleaner without parenthesis. - Chris Lutz
Fastest vs Easiest way to read a full file into a std::string.
string fast(char const* filename) {
ifstream file(filename, ios::ate);
int size = file.tellg();
file.seekg(0, ios::beg);
scoped_array<char> buffer(new char[size]);
file.read(buffer.get(), size);
return buffer.get();
}
string easy(char const* filename) {
ostringstream ss;
ss << ifstream(filename).rdbuf();
return ss.str();
}
Edit by Arrieta:
For the benefit of the community, and as a respectful extension to your clever post, I point out to code provided by Tyler McHenry [1]:
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
[1] http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstringfopen
. - bruce.banner
I also use this lexical cast in the few cases where linking to boost is undesirable, the only problem is that it does no error checking (but that can be easily added by checking the stream state before returning.
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
ss >> out
actually succeeds (and reads the whole of what's in the buffer of ss
), while yours fails to do so. If T2
is a POD, this will actually return _a random result. Makes for hours of debugging fun. - sbi
The following code implements a couple of list_sequence()
template functions that I find helpful for debugging. Basically, you can call:
cout << list_sequence(myVector, ", ") << "\n";
to list any standard container (such as vector<T>
or list<T>
) to stdout
, or more generally,
cout << list_sequence(begin, end, ", ") << "\n";
to list an arbitrary iterator range between iterators begin
and end
.
#ifndef SEQUENCE_LISTER_H
#define SEQUENCE_LISTER_H
#include <iostream>
#include <string>
#include <iterator>
template<typename X> class sequence_lister; // Forward reference
template<typename InIter>
inline std::ostream& operator<<(std::ostream& os, sequence_lister<InIter> const& sl) {
// copy(sl._first, sl._last, ostream_iterator<typename InIter::value_type>(os, sl._delim));
for (InIter i = sl._first; i != sl._last; ++i) {
if (i != sl._first) {
os << sl._delim;
}
os << *i;
}
return os;
}
template<typename InIter>
class sequence_lister {
public:
sequence_lister(InIter first, InIter last, char const* delim = "") :
_first(first),
_last(last),
_delim(delim)
{}
// Also allow construction from any container supporting begin() and end()
template<typename Cont>
sequence_lister(Cont& cont, char const* delim = "") :
_first(cont.begin()),
_last(cont.end()),
_delim(delim)
{}
sequence_lister(sequence_lister const& x) :
_first(x._first),
_last(x._last),
_delim(x._delim)
{}
sequence_lister& operator=(sequence_lister const& x) {
_first = x._first;
_last = x._last;
_delim = x._delim;
}
friend std::ostream& operator<< <>(std::ostream& os, sequence_lister<InIter> const& sl);
private:
InIter _first, _last;
char const* _delim;
};
template<typename InIter>
inline sequence_lister<InIter> list_sequence(InIter first, InIter last, char const* delim = "") {
return sequence_lister<InIter>(first, last, delim);
}
template<typename Cont>
inline sequence_lister<typename Cont::const_iterator> list_sequence(Cont& cont, char const* delim = "") {
return sequence_lister<typename Cont::const_iterator>(cont, delim);
}
#endif // SEQUENCE_LISTER_H
char *
since C++ gives them a special conversion for C-compatibility reasons, still it helps document the intention). Ideally I would change the Cont&
types to Cont const&
too, but I can't be 100% sure it won't break something... If anyone can spare the time to test that, by all means change it. - j_random_hacker
CCASSERT - force a compile-time assert
#define CCASSERT(predicate) _x_CCASSERT_LINE(predicate, __LINE__)
#define _x_CCASSERT_LINE(predicate, line) typedef char constraint_violated_on_line_##line[2*((predicate)!=0)-1];
Typical usage:
CCASSERT(sizeof(_someVariable)==4)
##
before processing! - Christoph
This class to trace the time spent on the execution of the expressions in the scope:
#include <iostream>
#include <sys/time.h>
class trace_elapsed_time
{
public:
explicit trace_elapsed_time(const std::string& msg, std::ostream& out = std::cout)
: msg_(msg), out_(out)
{
gettimeofday(&init_time_, 0);
}
~trace_elapsed_time()
{
timeval now;
gettimeofday(&now, 0);
double elapsed_seconds = now.tv_sec - init_time_.tv_sec +
now.tv_usec/1e6 - init_time_.tv_usec/1e6;
std::string::size_type pos = msg_.find("%t");
out_ << msg_.substr(0, pos) << elapsed_seconds
<< msg_.substr(pos+2, msg_.size()-1) << std::flush;
}
private:
std::string msg_;
std::ostream& out_;
timeval init_time_;
};
Example of use:
int main()
{
trace_elapsed_time t("Elapsed time: %ts.\n");
usleep(1.005 * 1e6);
}
Output:
Elapsed time: 1.00509s.
Note: You can make this code portable using boost time functions and linking against the corresponding library.
Note2: I recently found a very similar multiplatform utility in boost:
boost::progress_timer
[1]
Convert any streamable variable to string:
#include <string>
#include <sstream>
#include <iostream>
template<class Source>
string ToString(const Source& Value)
{
std::ostringstream oss;
oss << Value;
return ss.str();
}
See also Evan's lexical_cast [1] answer.
[1] http://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet#469718I can't post the code - it belongs to my employer, after all - but the thing I found most useful is
int number = 2;
sendMessage(makestring() << "This message has a " << number << " in it.");
IOW, in-place stream formatting. Implementation is left as an exercise to the reader (or maybe boost hast it :) ).
finally, my last answer is a string split function which splits on a single character delimiter of your choice.
inline void split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
Reading in a whole file, ISO-C:
size_t fget_contents(char ** buffer, const char * name, _Bool * error)
{
FILE * file = NULL;
char * temp = NULL;
size_t read = 0;
// assume failure by default
*buffer = NULL;
if(error) *error = 1;
do
{
file = fopen(name, "rb");
if(!file) break;
long size = fsize(file);
if(size < 0) break;
// no io error till now
if(error) *error = 0;
temp = malloc((size_t)size + 1);
if(!temp) break;
read = fread(temp, 1, (size_t)size, file);
temp[read] = 0;
// `temp` is needed because realloc may fail here!
*buffer = realloc(temp, read + 1);
if(!*buffer) break;
temp = NULL;
if(error) *error = (size != (long)read);
}
while(0);
// cleanup
if(file) fclose(file);
if(temp) free(temp);
return read;
}
return
- I could have used a goto
instead, but there would have been only one label; this was the nicest way I could think of to properly handle all possible error conditions and still close file
... - Christoph
return
s instead of break
s, and the function size would be reduced. - Carson Myers
Here is one of mines that I didn't saw it here (reproduced without a compiler, might not be exact):
class Monitor
{
private:
CRITICAL_SECTION cs;
public:
Monitor() { InitializeCriticalSection(&m_cs); }
~Monitor() { DeleteCriticalSection(&m_cs); }
void Lock() { EnterCriticalSection(&m_cs); }
void Unlock() { LeaveCriticalSection(&m_cs); }
};
class Locker
{
private:
Monitor& m_monitor;
public:
Locker(Monitor& monitor) : m_monitor(monitor) { m_monitor.Lock(); }
~Locker() { m_monitor.Unlock(); }
};
#define SCOPE_LOCK(monitor) Locker locker##__LINE__(monitor)
And it can be used like this:
class X : public Monitor {};
X x;
void use_x()
{
SCOPE_LOCK(x);
//use x
//on scope exit, x is unlocked
}
#include <queue.h>
Never write buggy linked list implementations again. [1]
#include <tree.h>
Never write buggy tree implementations again. [2]
Fully portable and legal for close-source commercial products.
[1] http://www.openbsd.org/cgi-bin/cvsweb/src/sys/sys/queue.hWith C++0x, I have a neat little string builder that I like to pass as arguments to exceptions, etc.
#include <sstream>
#include <iostream>
using namespace std;
void mksubstr(const ostringstream& stream)
{
(void)stream;
}
template<class T, class... Args>
void mksubstr(ostringstream& stream, const T& first, const Args&... rest)
{
stream << first;
mksubstr(stream, rest...);
}
template<class T, class... Args>
string mkstring(const T& first, const Args&... rest)
{
ostringstream buf;
buf << first;
mksubstr(buf, rest...);
return buf.str();
}
int main()
{
int x = 1, y = 10;
cout << mkstring("Foo: (", x, ", ", y, ")") << endl;
}
join()
or similar, but this is quite handy. - Jon Purdy
typedef boost::shared_ptr<Foo> FooPtr;
systematically getting team to use shared_ptr and using it in a common way
I've found myself writing the equivalent if the function too many times (sorry for typos):
template<class __p> static void deleteVector(std::vector<__p*>& target) {
for(std::vector<__p*>::iterator i = target.begin(); i != target.end(); ++i) {
delete *i;
}
target.clear();
}
Might be the perfect example of where to use some kind of smart pointer, but it's not all projects that uses that kind of coolness.
__p
is a reserved identifier.) - GManNickG
std::vector<int*> v = /* populate */; do_stuff(v); deleteVector(v);
. If do_stuff
throws, game over. This follows the same old principle: if you're ever in a position to manually free something, you've done it wrong. Wrap it up. - GManNickG
Thought there were far too few answers that can be used with C.
#include <getopt.h>
#define HAS_ARG 1
static struct option longopts[] = {
{ "option-a", HAS_ARG, 0, 'a' },
{ "option-b", HAS_ARG, 0, 'b' },
{ 0, 0, 0, 0 }
};
void show_usage(char* argvzero)
{
printf("%s usage\n", argvzero); /* more follows */
}
int process_args(int argc, char** argv)
{
/* do stuff to process the commandline options using <getopt.h> API */
};
I use this for adding debug logging that (a) disappears in non-debug code and (b) supports variable arguments. Similar to cojocar's answer [1] but doesn't use variadic macros (which aren't supported by all compilers):
extern int MyDebugLogRoutine( const char *fmt, ... );
#ifdef NDEBUG
#define Dprintf(x)
#else
#define Dprintf(x) MyDebugLogRoutine x
#endif
// need double parens
Dprintf(( "Format string that supports %s\n", "arguments" ));
[1] http://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet#470048MyDebugLogRoutine ( "Format string that supports %s\n", "arguments" );
. - Graeme Perrow
Dprintf
once with two parameters Dprintf('%s', 'abc')
and once with three Dprintf('%s %s', 'abc', 'def')
, the compiler would complain that Dprintf
only takes one parameter. I need to double the parens so that I really am calling Dprintf
with only one parameter. Perhaps some compilers allow this - the ones I use do not. - Graeme Perrow
#define Dprintf(x, ...) MyDebugLogRoutine(x, ##__VA_ARGS__)
This way you don't need the double parentheses. - Shahbaz
Stringify defined as ToString here [1]
Parse defined simetrically:
template <typename T>
void parse( std::string const & str, T & data )
{
std::istringstream st(str);
st >> data;
}
STL iterator printout (dump to stream) (maybe similar in functionality to sequence_lister here [2]?):
// dump to stream
class stream_dumper {
public:
explicit stream_dumper( std::ostream& o, std::string const & sep = "" )
: out_( o ), sep_( sep ), first_(true) {}
template <typename T>
void operator()( T const & t ) {
if ( first_ ) first_ = false;
else out_ << sep_;
out_ << t;
}
private:
std::ostream& out_;
std::string sep_;
bool first_;
};
// usage
void f( std::vector<int> const & v, std::list<double> const & l ) {
// dump the vertor separating with commas
std::for_each( v.begin(), v.end(), stream_dumper( std::cout, ", ") );
// dump the list separating with |
std::for_each( l.begin(), l.end(), stream_dumper( std::cerr, "|" ) );
}
I used to have a similar solution to free memory held in containers through pointers, but that code is now obsolete with the use of boost::shared_ptr
[1] http://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet#470262void
dprintf (char *format, ...)
{
#ifdef DEBUG
{
int rete;
va_list args;
static char buffer[1000000];//yes 1000000, I need this to debug
int ret;
va_start (args, format);
ret = vsprintf (buffer, format, args);
OutputDebugString (buffer);
printf (buffer);
}
#else
return;
#endif
}
Working with VTK the following defs were useful:
#define EPSILON 0.00001
// ex. if ( FLOAT_EQ(d,1) ) ...
#define FLOAT_EQ(x,y) ( ((x-EPSILON) < y) && (y < (x+EPSILON)) )
// Fit "val" to be between e1 and e2, just like vtkMath::ClampValue
#define FLOAT_CLAMP(val, e1, e2) \
{\
if ( (val)<(e1) ) (val)=(e1); \
if ( (val)>(e2) ) (val)=(e2); \
}
// 3D coordinate
#define FLOAT_COPY(src, dst) \
{\
(dst)[0]=(src)[0]; \
(dst)[1]=(src)[1]; \
(dst)[2]=(src)[2]; \
}
#define FLOAT_FILL(v, value) \
{\
(v)[0]= (v)[1]= (v)[2]=(value); \
}
#define FLOAT_SET(v, x,y,z) \
{\
(v)[0]=(x); \
(v)[1]=(y); \
(v)[2]=(z); \
}
Of course "const double epsilon = 0.00001;" and similar can be used instead of define. There's a CodeGuru article with explanations
What a coincidence! I'm just collecting mines here [1]. Everything is in C and is meant to be absolutely minimal, with as few dependencies as possible. At the moment I have:
It's a work in progress and I add code, examples and documentation when time permits. The code is for my own projects but is released under BSD should someone else find it useful.
[1] http://sites.google.com/site/clibutlThis is useful when working with sockets, it allows you to send a format string. The downside to this is that this function is that the output string limited to 8192. You could use asprintf
, but not all operating systems support this.
int sendf(int sock, char *format, ...) {
va_list args;
char buf[8192];
va_start(args, format);
vsnprintf(buf, 8192, format, args);
va_end(args);
return send(sock, buf, strlen(buf), 0);
}
My parallel-for\foreach macro; simple cut-and-paste from my parallel_for.h Also available at: http://dl.dropbox.com/u/9496269/parallel_for.h
/**
PARALLEL_FOR\PARALLEL_FOREACH
- Easy to use macro for making for/foreach loops run in parallel
- Uses boost::thread
- Contact: viktor.sehr [at] gmail.com
Examples of usage:
Traditional for-loop
transform:
for(size_t i = 0; i < container.size(); ++i) { container[i] = sin(container[i]); }
into:
pfor(i, 0, container.size(), { container[i] = sin(container[i]); });
BOOST_FOREACH or C++0x foreach loop
transform:
BOOST_FOREACH(auto& val, container) { val = sin(val); }
for(auto& val: container) { val = sin(val); }
into:
pforeach(auto& val, container, { val = sin(val); });
Traditional for-loop with specified range
transform:
for(int i = -1000; i < 1000; ++i){...}
into:
pfor(i, -1000, 1000, {...});
*/
#pragma once
#include <vector>
#include <boost/thread.hpp>
#include <type_traits>
// Default configuration
#define PFOR_NUM_KERNELS (::parallel_for::num_kernels_)
#define PFOR_THREAD_TYPE ::boost::thread
#define PFOR_THREAD_CONTAINER_TYPE ::std::vector<PFOR_THREAD_TYPE>
// Parallelism disabled?
#ifdef PARALLEL_FOR_DISABLED
#define PARALLEL_FOR SINGLE_FOR
#define PARALLEL_FOREACH PARALLEL_FOREACH
#else
#define PARALLEL_FOR PARALLEL_FOR_IMPL
#define PARALLEL_FOREACH PARALLEL_FOREACH_IMPL
#endif
namespace parallel_for {
inline unsigned get_num_kernels() {
auto val = boost::thread::hardware_concurrency();
return val == 0 ? 1 : val;
}
static unsigned num_kernels_ = get_num_kernels();
}
// PARALLEL_FOR
#define PARALLEL_FOR_IMPL(IDX, START_N, STOP_N, SCOPE) \
{\
typedef decltype(STOP_N) index_type_pfor; \
auto func = [&](index_type_pfor start_pfor, index_type_pfor stop_pfor) { \
for (index_type_pfor IDX = start_pfor; IDX < stop_pfor; ++IDX) { \
SCOPE; \
} \
}; \
index_type_pfor num_threads_pfor = static_cast<index_type_pfor>( PFOR_NUM_KERNELS ); \
index_type_pfor start_pfor = static_cast <index_type_pfor> (START_N); \
index_type_pfor stop_pfor = static_cast <index_type_pfor> (STOP_N); \
index_type_pfor distance_pfor = stop_pfor - start_pfor; \
PFOR_THREAD_CONTAINER_TYPE threads_pfor; \
threads_pfor.reserve(num_threads_pfor); \
for (index_type_pfor i = 0; i < num_threads_pfor; ++i) { \
index_type_pfor start = (distance_pfor/num_threads_pfor) * i; \
index_type_pfor stop = (i + 1 == num_threads_pfor ? distance_pfor : (distance_pfor/num_threads_pfor) * (i+1)); \
start += start_pfor; \
stop += start_pfor; \
threads_pfor.emplace_back( PFOR_THREAD_TYPE(func, start, stop) ); \
} \
for(auto it = threads_pfor.begin(), it_end = threads_pfor.end(); it != it_end; ++it) { \
it->join(); \
} \
}
// PARALLEL_FOREACH
#define PARALLEL_FOREACH_IMPL(VAR, CONTAINER, SCOPE) \
{ \
auto& container_pfor = CONTAINER; \
typedef decltype(container_pfor.begin()) iterator_type_pfor; \
auto func_pfor = [&](iterator_type_pfor start_pfor, iterator_type_pfor stop_pfor) { \
for (; start_pfor != stop_pfor; ++start_pfor) { \
VAR = (*start_pfor); \
SCOPE; \
} \
}; \
auto num_threads_pfor = PFOR_NUM_KERNELS; \
PFOR_THREAD_CONTAINER_TYPE threads_pfor; \
threads_pfor.reserve(num_threads_pfor); \
size_t step_pfor = container_pfor.size() / num_threads_pfor; \
iterator_type_pfor start_pfor = container_pfor.begin(); \
for (size_t i_pfor = 1; i_pfor < num_threads_pfor; ++i_pfor) { /* i starts at 1 as we only loop num_threads-1 times */ \
iterator_type_pfor stop_pfor = start_pfor; \
std::advance(stop_pfor, step_pfor); \
threads_pfor.emplace_back( PFOR_THREAD_TYPE(func_pfor, start_pfor, stop_pfor) ); \
start_pfor = stop_pfor; \
} \
threads_pfor.emplace_back( PFOR_THREAD_TYPE(func_pfor, start_pfor, container_pfor.end()) ); \
for(auto it = threads_pfor.begin(), it_end = threads_pfor.end(); it != it_end; ++it) { \
it->join(); \
} \
}
// SINGLE_FOR (for debugging\profiling)
#define SINGLE_FOR(IDX, START_N, STOP_N, SCOPE) \
{ \
typedef decltype(STOP_N) index_type_pfor; \
index_type_pfor start_pfor = START_N; \
index_type_pfor stop_pfor = STOP_N; \
for (index_type_pfor IDX = start_pfor; IDX != STOP_PFOR; ++IDX) { \
SCOPE; \
} \
}
// SINGLE_FOREACH (for debugging\profiling)
#define SINGLE_FOREACH(VAR, CONTAINER, SCOPE) \
{ \
auto& container_evaluated = CONTAINER; \
for (auto it = container_evaluated.begin(), it_end = container_evaluated.end(); it != it_end; ++it) { \
VAR = *it; \
SCOPE; \
} \
}
// Convenience macros
#define pfor PARALLEL_FOR
#define pforeach PARALLEL_FOREACH
#define sfor SINGLE_FOR
#define sforeach SINGLE_FOREACH
Before you write a double to the database, to avoid "Query error: Unknown column 'nan' in 'field list'" errors, apply the following wrapper:
static inline double SafeDouble(double const &d, double const def=0.0)
{
return (isfinite(d) && isfinite(-d))?d:def;
}
Determine a file's size with ISO-C:
long fsize(FILE * file)
{
if(fseek(file, 0, SEEK_END))
return -1;
long size = ftell(file);
if(size < 0)
return -1;
if(fseek(file, 0, SEEK_SET))
return -1;
return size;
}
stat
/fstat
on POSIX and GetFileSize(Ex)
on Windows covers you on 99.9% of all systems anyone cares about. Using these functions will almost assuredly be faster. - Adam Rosenfield
#define NuLog(str, args...) {\
fprintf(NULOG_OUTPUT, "Log (" NUMODULE_NAME "): " str "\n", ##args); \
fflush(NULOG_OUTPUT); \
}
Define NUMODULE_NAME in each component of your software and log to your heart's content.
In my C code, I often have dynamic array structures declared like this:
struct {
int num;
SomeType *list;
} foobar;
To make that easier in code where I'm iterating over those dynamic arrays a lot, I use this macro:
#define FOREACH(var,lst) \
for(i=0 ; (i<(lst).num?(((var)=(lst).list[i]),1):0) ; i++)
Which means I can then do this:
int i;
SomeType foo;
FOREACH(foo, foobar) {
/* Do something with foo here... */
}
While yes, it's not the world's most reusable (the i
is an issue, but that's awkward to fix and maintain strict C89 compatibility) it helps a lot because it means that I have my iteration code written correctly, once. I have another similar construct – FOREACH_HASH
– for iterating over the key/value pairs in hash tables, but that's more horrific and harder for other people to reuse so I won't repeat it here.
A very nerd one, which works if you are surrounded by nerds who do not care about code maintenance:
#define as ;while
int main(int argc, char* argv[]){
int n = atoi(argv[1]);
do printf("n is %d\n", n) as ( n --> 0);
return 0;
}
#include <glib.h>
When a class need to override the default copy constructor/assignment I sometime use something like this:
class SomeClass
{
struct Members
{
int a;
int b;
};
Members m;
int* evilptr;
public:
SomeClass(SomeClass const& rhs) : m(rhs.m), evilptr(new int(*rhs.evilptr))
{
}
~SomeClass(){ delete evilptr; }
SomeClass& operator=(SomeClass const& rhs)
{
m = rhs.m;
evilptr = new int(*rhs.evilptr);
return *this;
}
};
This way, if you add a new members to the class you can't forget to add it to the copy constructor/assignement operator. This save some possibility of error.
Of course in my exemple I could use some kind of clone_ptr but in real life this is not always this simple. Also beware that I never check for NULL in my exemple when dereferencing evilptr, you should of course adapt the code according to your needs.
[Edit]: I added a destructor for those complaining about memory leaks. Please note that I still omit a lot of checks as the point I was trying to illustrate was that with wrapping normally-copyable variable in a struct you don't need to update the copy constructor/assignment operator when adding/removing a variable from a class. That's the only point of my answer so please try to judge it on that and not on a bunch of other points not really related to the case.
new
without delete
or a smart pointer, and expect it to be viewed in a positive light. I could indeed change it myself, but what point it that? Also, for what reason is the evil pointer in there? What value should evilptr
get at construction? This feels more like an incomplete code snippet than like a code trick to me. - Jasper
When you need a custom copy constructor/assignment operator for one or more elements of your object, you can wrap all other objects in a struct so you won't need to update your copy constructor/assignment operator when changing the object. Like this:
and then give the code sample instead of just letting the code speak for itself (which it didn't do very well in my opinion). - Jasper