How should I encode stuff?

369 Views Asked by At

I'm generating code to encode various C++ structs in JSON using JSON spirit.

The generated code currently looks something like this:

Value _encode(df::tile_page rval){
    Object val;
    val.push_back(Pair("token",         encode(rval.token)));
    val.push_back(Pair("filename",      encode(rval.filename)));
    val.push_back(Pair("tile_dim_x",    encode(rval.tile_dim_x)));
    val.push_back(Pair("tile_dim_y",    encode(rval.tile_dim_y)));
    val.push_back(Pair("page_dim_x",    encode(rval.page_dim_x)));
    val.push_back(Pair("page_dim_y",    encode(rval.page_dim_y)));
    val.push_back(Pair("texpos",        encode_vector<int32_t>(rval.texpos)));
    val.push_back(Pair("datapos",       encode_vector<int32_t>(rval.datapos)));
    val.push_back(Pair("texpos_gs",     encode_vector<int32_t>(rval.texpos_gs)));
    val.push_back(Pair("datapos_gs",    encode_vector<int32_t>(rval.datapos_gs)));
    val.push_back(Pair("loaded",        encode(rval.loaded)));
    return Value(val);
}

However I think it will be difficult to figure out if people are passing structs, pointers to structs or references. I'm new to C/C++ so some of the subtleties are a bit beyond me.

I was thinking of creating multiple versions of _encode for each struct, ie. (df::tile_page, df::tile_page*, df::tile_page&, df::tile_page**, etc)... but this seems unnecessary?

I wanted to create a template to dereference stuff, however I've not been able to work it out. I've tried using a dereference template however kept getting undefined symbol errors.

undefined symbol: json_spirit::Value_impl<json_spirit::Config_vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > encode<df::world>(df::world*)

Current templates:

template<typename T> T & dereference(T &v) { return v; }
template<typename T> T & dereference(T *v) { return dereference(*v); }

template <class T>
Value encode(T x) {
    return _encode(dereference(x));
}

template <class T>
Value encode(T* x) {
    return _encode(dereference(x));
}

The main idea is: To encode something you call a template that dereferences it then passes it on to the generated functions. They in turn call the dereferencing templates to encode any of their fields.

0

There are 0 best solutions below