Friday, December 30, 2011

Access to private members: Safer nastiness.

In one of my previous posts I showed some code that accesses a private member, that now has been posted on the boost mailing list as a possible utility for boost serialization to access private attributes (OH MY, I had no idea such a thing actually could have uses!).

I realized that it would be beneficial to have an alternative implementation because the previous code suffered from the Static Initialization Order Fiasco. The following code does not suffer from that problem anymore:

template<typename Tag, typename Tag::type M>
struct Rob { 
  friend typename Tag::type get(Tag) {
    return M;
This defines a friend function that can be called by ADL using the tag type.
// use
struct A {
  A(int a):a(a) { }
  int a;

// tag used to access A::a
struct A_f { 
  typedef int A::*type;
  friend type get(A_f);

template struct Rob<A_f, &A::a>;

int main() {
  A a(42);
  std::cout << "proof: " << a.*get(A_f()) << std::endl;
Note that the explicit declaration of "get" inside of "A_f" is important, because we want "get" to be visible to ADL, and the rob template specialization is not an associated class of "A_f" (we could have declared it globally too, if we wanted, but then it would be visible for anyone). To overcome that, we could introduce some utility class we derive from:
template<typename Tag, typename Member>
struct TagBase {
  typedef Member type;
  friend type get(Tag);

The definition of a Tag then becomes very simple
struct A_f : TagBase<A_f, int A::*> { };
Unfortunately with the TagBase, GCC spits out a warning about the "friend type get(Tag)" that it declares a non-template function. The warning can be ignored, but it's annoying :).

Hope you enjoyed!

Saturday, November 27, 2010

Fun with switch statements

Since my coworker proudly told me about some switch macro he created for himself with C that can process strings, I thought I wanted to do that too, but with C++. Here is what I ended up with.
#include <boost/typeof/typeof.hpp>
#include <cassert>

/* Store a value of type V */
template<typename V>
struct S {
  operator int() { return -1; }
  S(V const& data):data(data), matched(false) { }

  V data;
  bool matched;

#define sswitch(V)                                      \
  switch(S<BOOST_TYPEOF(V)> _s_ = V)                    \
  case -1: { if(0)                                           

#define scase(V)                                        \
  } if(!(_s_.matched || == V)) ; else          \
    if(!(_s_.matched = true)) ; else { case __LINE__

#define sdefault() \
  } default

#define snodefault(MSG) \
  } do { assert(!MSG); __builtin_unreachable(); } while(0)
That looks pretty weird! What are its drawbacks?
  • A default case must always be present and must be put last
  • Can't put a block around several cases, so sswitch is incompatible to Duffs device.
  • The to-be-switched value is always copied - there is no automatic deduction for lvalues such that they would use references and that only rvalues would be copied
On the goodness sides, sswitch can use native break keywords with the expected semantics, works with any type (not just strings) and also supports fall-through like the built-in switch. Here is how it can be used.
  sswitch(s) {
    scase("foo"): {
      std::cout << "s is foo" << std::endl;
      break; // could fall-through if we wanted

    // supports brace-less style too
      std::cout << "s is bar" << std::endl;

    // default must be at the end
      std::cout << "neither of those!" << std::endl;
Notice that since we insert extra braces between each case label (to prevent the code in between to be executed if we haven't hit a label yet), we can't use a plain "default:" at the end, as would be desired by me. We can jump inside if we want
  sswitch(s) {
    std::cout << "this will be output after foo/bar!" << std::endl;

    scase("foo"): {
      std::cout << "s is foo" << std::endl;
      goto test;

    // supports brace-less style too
      std::cout << "s is bar" << std::endl;
      goto test;

    // default must be at the end
    snodefault("neither foo nor bar!?");

Please tell me what you think about it and whether you find any problem! Hope you like this little helper!

Saturday, July 3, 2010

Access to private members. That's easy!

So, always thought that it's impossible without undefined behavior to access private members of arbitrary classes without being friend.

Today I noticed I've been horribly wrong, after reading some insightful commit to the clang compiler, that enabled it to allow explicit instantiation to disregard accessibilities, as per the Standard. This enables us to access private members of others. As an experiment, I created some class templates

template<typename Tag>
struct result {
  /* export it ... */
  typedef typename Tag::type type;
  static type ptr;

template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;

template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
  /* fill it ... */
  struct filler {
    filler() { result<Tag>::ptr = p; }
  static filler filler_obj;

template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;

So, how is it used? Let's have an example

struct A {
  void f() {
    std::cout << "proof!" << std::endl;

struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;

Ah, that's all to expose poor A's "f" member. Now anyone can use them using the member pointer snytax, as does the main function below

int main() {
  A a;

Of course, as Herb Sutter told us, don't do these things in real code.

Saturday, November 1, 2008

My new blog and a Pacman surprise

Hello there.

So now I've read many blogs out there. And I think it's time that I also own some blogs about what I'm doing with my spare time and whatnot :P So I came across and thought it would be a good idea to get my hands dirty and create one. So here we are.

First of all I want to tell you that pacman.d mirrorlist is sometimes really not ordered all that well :P So after waiting another round of minute for the VLC package to download completely, I figured it would be the best to just sit down and write this script:

trap "rm -f $tmpf; exit" INT TERM
gawk '
/#?Server =/ {
  host = gensub(/^[^:]+:\/\/([^/]+).*/, "\\1", 1, $3)
  print host, $0
}' /etc/pacman.d/mirrorlist |
while read host line; do
  echo "trying to ping '$host'" >/dev/stderr
  timed=$(ping -i 0.3 -c 1 -W 1 -n -q $host 2>/dev/null |
    tail -n1 |
    gawk '{ print $4 }' |
    cut -f2 -d/)
  [ x != x$timed ] && echo $timed ${line%#*};
done | LC_ALL=C sort -n | 
while read crap remains; do
  echo $remains \# $crap ms;
done > $tmpf

echo 'the following was created: '
cat $tmpf
echo -e '\nwant me to use it? (y|n)'
read reply
if [ x$reply = xy ]; then
  mv $tmpf /etc/pacman.d/mirrorlist
  rm -f $tmpf

What does it do? Well, it basicially finds out the currently best order for the mirrorlist file, so that the fastest mirror is at the top. After running it, I was really impressed about the speed of pacman. It rushed through like a tiger :P