Calculating the number of elements of an underlying data structure
Don't Repeat Yourself

Your looping code appears twice. Once in the body of size() and once in the body of GoRec::size(). You only need it once. In fact, the entire structure of GoRec is kind of weird and unnecessary. I also don't like how you named the function go(), made it void, and have it take a reference... Instead, let's write a free function:

size_t size_of(AnyMap const&amp; data)
{
    size_t size = 0;
    for(const auto&amp; kv : data){
        if(kv.second.type() == typeid(AnyMap)) {
            size += size_of(any_cast&lt;const AnyMap&amp;&gt;(kv.second));
        }
        else{
            size++;
        }
    }        
    return size;
}


That way:

int size() const {
    return size_of(data);
}


And we have no repetition and no unnecessary extra case for empty map.

Know Your Interface

There are several different overloads for boost::any_cast. You are using the wrong one. This is the one you want:

template&lt;typename ValueType&gt; const ValueType * any_cast(const any * operand);


This overload will not throw, and will return a null pointer if you're attempting to cast to the wrong type. Now, the overload you're using will throw if it's the wrong type - but you're explicitly checking that first. Effectively, you're re-implementing what any_cast is doing under the hood, which is bad.

If you used the other overload, you could let the any internal implementation remain private. And the code ends up looking more direct:

size_t size_of(AnyMap const&amp; data)
{
    size_t size = 0;
    for(const auto&amp; kv : data){
        if (auto submap = any_cast&lt;AnyMap&gt;(&amp;kv.second)) {
            size += size_of(*submap);
        }
        else{
            size++;
        }
    }        
    return size;
}