kastnermario / yaml-cpp

Automatically exported from code.google.com/p/yaml-cpp
MIT License
0 stars 0 forks source link

Using templated conversion operators to bypass the need for the as<> function #249

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
While working on a similar project (that will probably be replaced by yaml-cpp) 
I developed a nice way for handling conversion to native datatypes.

As it should be a very small addition to add to yaml-cpp and would provide the 
benefits of "magic" looking code. I would like to suggest that it be considered 
for inclusion.

It works by templating the conversion operator so that when the c++ compiler is 
trying to find a valid conversion, it will try a substitution (and possibly get 
one).

You could chain this directly with the existing as operator to make it 
seamlessly blend into the codebase.

The conversion doesn't always work (if it's ambiguous) but for most cases it 
can make the code appear much more natural.

I have attached a complete working example.

Original issue reported on code.google.com by tr...@houliston.me on 6 Jun 2014 at 8:53

Attachments:

GoogleCodeExporter commented 8 years ago
yaml-cpp used to have this. See Issue 150 for some reasons, and discussion 
about this. The short version: there's ambiguity with operator bool().

I've started coming around to something like this:

{{{
Node node = Load("[4, 7]");
int x = node[0].as<int>();
int y = node[1]();
}}}

The idea is that operator() returns a fake object that has a templated 
conversion method.

Original comment by jbe...@gmail.com on 6 Jun 2014 at 9:28

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago

Original comment by jbe...@gmail.com on 24 Jan 2015 at 11:26