0

I'm writing a C++ opensource project for configuration loading (from tree data structures like xml and json) based on boost::ptree and boost::lexical_cast.

To allow implicit conversion from a Tree structure to any primitive or user defined types, I've added a conversion operator template:

template<class Type>
operator Type() const {
    return boost::lexical_cast<Type>(this->toString());
}

full code here

This works with types handled by boost::ptree. For all other types, the user can specialize this template:

namespace swiftree {
template<>
Tree::operator Vector3() const {
    Vector3 ret;
    ret.x = value<float>("x");
    ret.y = value<float>("y");
    ret.z = value<float>("z");
    return ret;
}
}

So the user con do this:

Vector3 position = tree["position"];

Are there any drawbacks to using such technique? Are there better alternative ways to achieve the same?

Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63
  • Boost ptree already has a similar feature. Look at http://stackoverflow.com/questions/9745716/change-how-boostproperty-tree-reads-translates-strings-to-bool You can add translators to all types you need – user1781290 Oct 24 '14 at 10:07
  • The idea behind this project is to have a more concise way to get data than ptree has. `translator_between` seems to be an alternative to the operator template... but why it's better? – Alessandro Pezzato Oct 24 '14 at 10:22
  • This might depend on needs and opinion. I intentionally created only a comment, since I don't want to say it's better or worse. I'm fine with using a standard `ptree`, depending on your needs your `operator` approach might be better – user1781290 Oct 24 '14 at 10:37
  • The opinion of many in the C++ community has gradually become "implicit conversions are evil". They frequently create a mess with overload resolution and generic code – sehe Oct 25 '14 at 22:24

0 Answers0