views:

6508

answers:

35

It seems that every project has an "utility" module with various code snippets used throughout other files and which don'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.

+15  A: 
#define ever ;;

Example use:

for(ever) { ... }
Cody Brocious
Nice trick... But I'm not sure if people won't find while(true) to be more explicit ?
Wookai
while(true) will produce a warning on some compilers because the condition is a constant.
Evan Teran
It wasn't meant as a serious suggestion by any means.
Cody Brocious
lol, people like it. Though, I'd prefer: #define forever for(;;) that way you can just write: forever { ... }
Evan Teran
for(;"ever";)
what(ever) {...}
Baltimark
@Baltimark: no problem: `#define what(IGNORE) for(;;)`
Christoph
+1 funnyNicely done.
Rodyland
It is funny, but not really useful.
Ismael
Nice one lraimbilanja.
j_random_hacker
How about: #define ty int n = 0; n < 40; n++
Daniel Earwicker
@Earwicker: or `#define ty_two ;;) puts("DON'T PANIC"` so that you can do `for(ty_two);`
Christoph
Sorry, but I don't like this. ;; is shorter to type than "ever", and who doesn't recognize this construct? "ever", though, must make you think once more. while (1) is the best here, IMHO
Eli Bendersky
Haha what a funny one. I'd do while(true) though
Ray Hidayat
-1, that's horrible
Patrick
Macros are generally bad. If somebody names something "ever", that'll be a hard-to-track-down bug.
David Thornley
hate it. Prefer while (1)
jmucchiello
@Iraimbilanja: That's much nicer!
Johnsyweb
+25  A: 

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 &ltrim(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));
}
Evan Teran
Do they modify the input string and return it? Why?
1800 INFORMATION
Evan Teran
gosh, c++ scares me :-)
Eli Bendersky
Michael Burr
Good point, in the end the documentation should make it abundantly clear that the function modifies its input.
Evan Teran
You should also make the predicate a parameter so you can trim things other than spaces.
jmucchiello
an optional parameter defaulting to spaces
advs89
+11  A: 

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;
}
Evan Teran
most of boost is in headers, you shouldn't have to link to anything in boost to get boost::lexical_cast<>
fair enough, but every now and then I'm on a system where boost isn't immediately available.
Evan Teran
This is true - try to convince your management and/or team to bring in an open source lib (even if it's all headers) that they are unfamiliar with. It tends to elicit much fear.
Michael Burr
@Michael Burr: precisely. There are too many answers to very trivial question (e.g. trim) that say "use boost"!
Stuart
A: 
#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.

Cody Brocious
+9  A: 

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.

sequence_lister.h

#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
j_random_hacker
Thanks Evan :) It's the only utility-type thing I've written that I now can't live without...
j_random_hacker
Why didn't you use the copy algorithm that you have commented out?
Harper Shelby
cause it will put a delimiter after the last item perhaps?
Evan Teran
Shouldn't delim be const char*?
jmucchiello
j_random_hacker
A: 

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;
}
Christoph
On binary files this will work fine, but if they're opened in text mode, you may be in for a surprise... http://www.cplusplus.com/reference/clibrary/cstdio/ftell.html
rmeador
"In the GNU library, and on all POSIX systems, there is no difference between text streams and binary streams. When you open a stream, you get the same kind of stream regardless of whether you ask for binary."
Christoph
Windows has some issues with non-text files opened in text mode and auto-converts \r\n to \n (this isn't an issue when determining the size of a buffer needed to hold the file's contents); this has an easy fix: always open files in binary mode!
Christoph
Wouldn't stat or fstat be alot better suited for this purpose?
roe
@roe: these functions are not part of the ISO-C standard library
Christoph
Is filelength() part of ISO-C?
Ferruccio
Ferruccio: Does it have all of its vowels? Yes? So obviously not in ISO-C!
jkerian
@Christoph: `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
+7  A: 

I 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 :) ).

Arkadiy
Very nice! Lemme guess: makestring() produces an object of some type derived from ostream, which has an implicit conversion to char*.
j_random_hacker
Actually... Wouldn't that mean that the temporary returned by makestring() actually gets destructed before sendMessage() gets called? Do you use a static or preallocated char buffer to avoid that?
j_random_hacker
it could always have cast to std::string overloaded... then no scope issues.
Evan Teran
To j_random_hacker: "Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created." (12.2/3)
makestring is a class, and it has a templated operator << to transfer the call to the ostringstream it owns, plus another one for manipulators.
Arkadiy
Really nice idea :) Since your code is not free, I will post my own implementation as an anwer.
David Rodríguez - dribeas
Thanks lraimbilanja. I realise now: everything works provided the temporary is created at the top lexical level. It's only if a function called by the top level expression creates a temporary and returns its address or the address of one of its members that the temporary gets destroyed too early.
j_random_hacker
Google uses that for their logging class. So your employer is.... :)
Andrei Taranchenko
j_random_hacker: Yep.
Andrei: I wish...
Arkadiy
+7  A: 

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);
    }
}
Evan Teran
We have s.find_first_of(delim) instead of getline. Which one works faster?
Igor Oks
Does it matter? How often is a string split the time limiting step in your application?
Martin Beckett
+3  A: 

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;
}
Christoph
why do { ... } while (0) ???
Marcin Koziuk
@marcin: to be able to skip code without using `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
A neat demonstration of how goto is sometimes better! Would be much clearer in this case.
Daniel Earwicker
But when programming C, you get used to the do...while(0) abuse: it's pretty common when defining multi-statement macros...
Christoph
Also, I believe it's a common pattern in the one-exit-point-per-function camp...
Christoph
sorry for replying to this while it's sooo old, but shouldn't that whole do { ... } while(0) construct just be replaced with another function call? Then there'd be less questionable code, you could use `return`s instead of `break`s, and the function size would be reduced.
Carson Myers
@Carson: see if you can refactor the code and make it more clear while still handling all error cases the same way; I couldn't do it, but perhaps you can
Christoph
I'm confused. If the fread doesn't read the whole file shouldn't you loop and do another fread for the rest of the file? That's what I usually do.
jmucchiello
The do...while(0) "abuse" is interesting. Since I am C++-only I like learning C-idioms - because I have to work with C pretty soon...
vobject
+2  A: 

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.

Laserallan
I have something like this, it's very useful! I instead only declare a DeletePointer functor and do it this way: for_each(v.begin(), v.end(), DeletePointer());
Ray Hidayat
Doubt your code is exception safe. You should use a container of smart pointers or a pointer container. (And `__p` is a reserved identifier.)
GMan
@Gman: any code that throws exceptions in destructors is insane anyway. So I think that it is ok exception wise.
Evan Teran
@Evan: I mean `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.
GMan
@GMan: gotcha, fair enough.
Evan Teran
+7  A: 

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)
plinth
In which compiler is this supposed to work? The __LINE__ macro won't be expanded, because it will be joined via `##` before processing!
Christoph
compile time asserts are very useful, but currently awkward to make work on all compilers. The new C standard is defining static asserts though. More details here: http://www.pixelbeat.org/programming/static_assert.html
pixelbeat
Consider using [Boost's static assert](http://www.boost.org/doc/libs/1_42_0/doc/html/boost_staticassert.html) instead.
Seth Johnson
+30  A: 

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.

Edit: use NDEBUG which is standard.

cojocar
Why not check for `NDEBUG`, 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
Now I can upvote in good conscience: +1
Christoph
+10  A: 

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:

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
                 std::istreambuf_iterator<char>());
Interesting, but is there no way to avoid the string copy?
StackedCrooked
@StackedCrooked: No extra copy will be created here. Google for Return Value Optimization.
missingfaktor
+49  A: 

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 and Imperfect C++, by Matthew Wilson, section 14.3.

Josh Kelley
Microsoft now has _countof() in stdlib.h which is very similar.
Rob K
Very nice! That's the first time I've ever seen the fact that x[y] === y[x] being *useful*!
j_random_hacker
Cool, didn't know about 0[arr]. +1
Zach Langley
+1 from another Matthew Wilson reader.
Michael Burr
You should drop the parents: "sizeof arr" is enough; sizeof is not a function.
unwind
If you're using C++, you shouldn't be using arrays at all. Use vectors.
Rocketmagnet
How come the macro works with char arr[10] but not with char *arr ?
Naseer
@Naseer: The macro gives incorrect results work with char *arr because C and C++ don't know the size pointed to by a pointer. The template version intentionally fails to compile when used with char *arr for this reason.
Josh Kelley
@Josh - I thought in char arr[10] arr is also a pointer. How is the size known for that array ? Shouldn't the size in this case also be the size of the pointer ?
Naseer
@Naseer: char arr[10] is in most respects a pointer, but sizeof (in the macro version) and certain template parameters (in the second version) still know that it's an array. Once you pass char arr[10] to a function taking char* as a parameter, the array decays into a pointer, and C/C++ can no longer distinguish the two or know the array's size.
Josh Kelley
Thank you - that was very informative !
Naseer
Very cool. Why not leave the function unimplemented to produce a link error if used outside `sizeof`?
Potatoswatter
Not downvoting; but I have to ask: where would you ever use this? Every time I've had an array of known size, it's because the size is some easily available expression such as `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
+5  A: 

Convert any streamable variable to string:

#include <string>
#include <strstream>
#include <iostream>
using namespace std;

template<class Source>
string ToString(const Source& Value)
{
    strstream ss;
    ss << Value << '\0';
    string os = ss.str();
    ss.freeze(false);
    return os;
}

See also Evan's lexical_cast answer.

Igor Oks
you should take a look at my "lexical_cast" answer above, it lets you go both to and from a string.
Evan Teran
you are right. though this one is doing it without the second type (but 1 direction only :-])
Igor Oks
In most cases for my answer, you can omit the second type like this:int x = lexical_cast<int>("12345");because the compiler can figure out the type of the parameter.
Evan Teran
is the '\0' really required? And what would be the consequence of simply returning ss.str()?
Stuart
and why use strstream rather than stringstream?
Stuart
@hapalibashi: because this snippet is quite old. Feel free to edit it.
Igor Oks
+1  A: 

I use this for adding debug logging that (a) disappears in non-debug code and (b) supports variable arguments. Similar to cojocar's answer 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" ));
Graeme Perrow
Why isn't the #else: #define Dprintf(x) MyDebugLogRoutine **(** x **)**?
jmucchiello
@jmucchiello: The first set of double parens gets "absorbed" by the macro, so the macro expands to `MyDebugLogRoutine ( "Format string that supports %s\n", "arguments" );`.
Graeme Perrow
Right, so if you did the #define with parens you wouldn't have that problem. This is the normal idiom: #define func(x) hiddenfunc(x)
jmucchiello
If I wanted to call `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
+1  A: 

Stringify defined as ToString here

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?):

// 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

David Rodríguez - dribeas
For stringify/parse, check out boost's lexical_cast.
Daniel Earwicker
+21  A: 

My own implementation of make_string() as proposed here by Arkadiy:

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'

David Rodríguez - dribeas
Very nice dribeas. Can I suggest adding an operator const char*() conversion as well, since many libraries still take C-style strings? They won't conflict. I also found that MSVC++9 needs a 2nd operator<<() template that binds to non-const ref for handling some manipulators.
j_random_hacker
Well, the compiler also won't complain if you try to assign (make_string() << ...).c_str() to your str variable, which is the same thing IMHO -- in both cases you have to accept that there are parts of a contract that can't be enforced by the language. But it's up to you of course.
j_random_hacker
I was about to mention that you could add a std::string member variable to solve the problem of the temporary in operator const char*(), when I saw you had done so yourself! So I think this removes any "danger." But I agree that c_str() is a more explicit (e.g. greppable) way to indicate danger.
j_random_hacker
You can fix the char const* storage problem by treating the string maker as a global resource. http://pastie.org/375016 But it's not threadsafe and it still lets you do `char const* hi=string_maker << "Hello world"; char const* bye=string_maker << "Bye"; cout << hi;`. Guess its best to just say no.
Why not use boost::lexical_cast?
Matt Fichman
your implementation currently doesnt support stream manipulators like `std::endl`, why not add it ?
smerlin
@smerlin: The main reason is that I have never actually needed it, over one year of usage. In your particular case you can add '\n' (`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
+4  A: 
#include <queue.h>

Never write buggy linked list implementations again.

#include <tree.h>

Never write buggy tree implementations again.

Fully portable and legal for close-source commercial products.

HUAGHAGUAH
Um, tree.h is not portable it's BSD. Whereas queue is portable but not in the <queue.h> form (which is either BSD or old C++), rather in the <queue> form (which is standard C++).
Sometimes it would be useful to have a tree type, but the Standard C++ Library has linked lists and queues pretty well covered, as well as sets and maps for doing what most people want to use trees to do (they're trees underneath).
j_random_hacker
A: 

What a coincidence! I'm just collecting mines here. Everything is in C and is meant to be absolutely minimal, with as few dependencies as possible. At the moment I have:

  • Debugging macros (similar to what cojocar already showed)
  • Logging macros (similar to log4j but only logs to file)
  • Unit testing framework (produces a TAP compliant result)
  • Variable length strings (that can be intermixed with C strings)
  • Associative arrays (where keys and values can be strings, integers, pointers or other tables)
  • Pattern matching (different from regular expressions). Used with the variable length strings it offers search and replace functionalities similar to what many scripting languages 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.

Remo.D
+17  A: 

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(typename 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.

Daniel Earwicker
This is extremely cool. This is going in my utility library, along with makestring().
j_random_hacker
In C++ _StringBuffer is a reserved identifier, shouldn't be used for your own class template.
robson3.14
+4  A: 

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
}
Nice use of RAII.
j_random_hacker
Two notes - CRITICAL_SECTION is win32, so this isn't cross-platform. Also, the Boost threading library can do pretty much the same thing with boost::lock_guard http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html
Branan
Hi, thanks for the comment.Cross-platform-ness is not an issue for me. And the sample can be easily adapted for other platforms. Didn't knew about boost::lock_guard. I'll look into it.
check out the MFC CCriticalSection and CSingleLock equivalents.
gbjbaanb
Shouldn't these classes be made non-copyable?
StackedCrooked
+33  A: 
#include <boost/...
Ferruccio
(+1) But I think the asker meant quick hacks of 100 lines of less.
Arrieta
"#include <boost/..." is a quick hack of 100 lines or less.
tstenner
@tstenner: good point.
Arrieta
A: 
void
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


}
Arabcoder
not doing much multithreaded work ? static is really not gonna work then
Bahbar
yes , I agree , sorry
Arabcoder
A: 

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.

n1ck
I'm confused, does this not leak all over the place? You need the Big Three, and the pointer should be wrapped up.
GMan
@GMan: The point I was trying to illustrate was that Members do not need to be updated in the copy constructor and the assignement operator by wrapping it in a struct. The rest is left to the reader. As it is community wiki you're of course welcome to ameliorate it and you're also welcome to use the type of pointer that you prefer.
n1ck
You can never provide a code with `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
@Jasper: please let me LOL. Sorry I read my answer again and maybe when reading fast I understand that you did not get the trick. Read my comment to GMan above. Memory management, smart_ptr or the value of the pointer is in no way important in the code sample so was omitted. The point is that you don't have to update the copy constructor when adding/deleting a member of a class by wrapping them in a Member struct. The pointer is to illustrate a member that should not be copied normally -- and nothing else ,that's why I didn't took care of deleting it.
n1ck
Also, to clarify, in the exemple, we could use a deep_copy_ptr (that's what I meant by clone_ptr I guess) but then it would destroy the exemple as it could then be added to the members struct without any problem. The point is that in real life some pointer need special care so cannot be copied normally. This is the point of the trick -- not needing to update those variable than can be copied normally. Sorry if my answer was not clear enough. It is noted and I will see what I can do about it.
n1ck
@n1ck: If that's how it is, your presentation is clearly in the way of your point - I really didn't get it. Perhaps you could start off with something like `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
@n1ck: Additionally, you could provide a comment at the evilptr code, explaining that it is not a part of the trick, but just something you needed a custom copy constructor for, that will provide a lot of clarity. Also, I would say that a code sample may leave a lot to the reader (like making a class useful in any way) and may make certain assumptions about added functions if noted (like assuming that other functions don't modify your pointer), but I do think code samples should work all on their own... As such, I would recommend adding a normal constructor or using std::auto_ptr
Jasper
I still don't see the point. Bad practice, use the [copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom).
GMan
@GMan: see my new answer: http://stackoverflow.com/questions/3648797/why-would-a-copy-constructor-have-more-than-one-parameter/3652740#3652740. You're right that it do not use the copy-and-swap idiom though but I was not totally sure how to implement the most optimal copy construction so left it to the reader for the moment.
n1ck
@n1ck: What I mean is I still don't see the point, and until you clarify this and finish it, nobody will. You're the only one who knows what you *intend* with it. There's no point in sticking all the members into a struct just to make copying easier, when you can properly implement copy-semantics with the copy-and-swap idiom, which is cleaner.
GMan
@GMan: Did you read my new link or what? It clearly indicate a use case. I have a bare pointer that is only an alias and the other members should be copied normally. I don't see how the copy-and-swap idiom would help in that case. It would surely improve the code I agree with you but it will not solve my problem.
n1ck
@n1ck: Yes, it doesn't clarify anything. Again, all you're giving is intent (I fix problem x by doing y), but fail to actually explain problem x or problem y in detail. We don't know what the members are, what the pointers for, why you need to do it this way, etc. The code, as it stands, leaks and is incomplete. You *really* need to give concrete examples when you present an idea.
GMan
@GMan: Well I didn't want to post full code at the time. With the new post you should be able to tell what it is about. If you work with deep copy it is possible you have experienced the need to do something like this. Before I knew of this trick I just copied the values in the copy constructor instead, one by one, but was error prone. I just wanted to share it with the stackoverflow community so that they know there is a better way to do things and now you're complaining about that the code is not perfect. Yes I aknowledged that point, now move on, please.
n1ck
@n1ck: I can now, but honestly the code would be better off using the copy-and-swap idiom then this idiom, in my opinion. My complaint is that when you say "do this", the "this" part needs to be complete and well. It still leaks, as it stands. I get the point, it's just that the point is lost around all the bad stuff.
GMan
@GMan: Just think the pointer as representing the "parent" (enclosing class) pointer in my other answer. It do not need to be copied when deep copying. The values (POD) should be copied, the pointer need to point to the correct memory location which the parent know during the copying. When the parent is copied it pass the pointer value to the child (each child need to know about the parent if you will) but this pointer is not updated in the normal way. This solution prevent that (and possibly other problems) that is the reason why I want to post it.
n1ck
@GMan: I just read your answer about copy-and-swap and I don't know why you sent me there because it suffer exactly from the problem that I say I have fixed: what happen when you add a value to your dummy_array class and forget to update the swap function -> bug (possibly not detected directly too - it might crash way later). By wrapping the members in a struct you don't have to remember to update those values that should only be copied normally.
n1ck
@GMan: I edited my other answer with a code sample if you're interested.
n1ck
A: 

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

CC
http://www.codeguru.com/forum/printthread.php?t=323835
CC
ya might consider using the epsilon values from math.h
EvilTeach
+6  A: 

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

fnieto
+11  A: 

A simple hexdumpis 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");
  }
}
epatel
+9  A: 

This is EVIL! I know, but has come in handy:

#define private public
 #include "OhSoEncapsulatedLittleObject.hpp" // Let me at'em!
#undef private
S.C. Madsen
+1; also `#define protected public` and `#define class struct`
David X
Absolutely! I use this from time to time when writing tests for class libaries, where I want to check post-conditions on private members on the classes.
S.C. Madsen
You left out the #undefs
jmucchiello
I added the #undef
ufotds
+1  A: 

typedef boost::shared_ptr<Foo> FooPtr;

systematically getting team to use shared_ptr and using it in a common way

pm100
A: 
#include <glib.h>
ahe
+1  A: 

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 */
};
James Morris
A: 

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;
}
Arrieta
A: 

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.

Donal Fellows
+1  A: 

With 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;
}
Maister
I would call it `join()` or similar, but this is quite handy.
Jon Purdy