g++ trick for initializer lists

A couple of g++ extensions can give something like the proposed c++0x initializer lists, at least when it comes to initializing sets and vectors.
#include <iostream>
#include <set>

#define ARRAY_ELEM(x) (sizeof(x) / sizeof(*x))
#define ARRAY_END(x) (x + sizeof(x) / sizeof(*x))
#define MAKE_CONTAINER(T, i, ...) ({ \
    static const __typeof__(i) _arr[] = {i,##__VA_ARGS__}; \
    T(_arr, ARRAY_END(_arr)); \
})
#define MAKE_SET(i, ...) MAKE_CONTAINER(std::set<__typeof__(i)>,i,##__VA_ARGS__)

#define IN(v,c) (c.find(v) != c.end())
int main(void) {
    std::set<int> s(MAKE_SET(1,3,7,21,13));

    for(int i=0; i<30; i++)
        if(IN(i,s))
            std::cout << i << " ";
    std::cout << "\n";
    return 0;
}


Entry first conceived on 12 May 2009, 14:33 UTC, last modified on 15 January 2012, 3:46 UTC
Website Copyright © 2004-2024 Jeff Epler