$include_dir="/home/hyper-archives/boost/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [boost] PCL - Portable C++ Library
From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2012-02-11 09:37:52
On 02/11/2012 02:39 AM, paul Fultz wrote:
> How would you use a switch?
>
> My design works by creating a metadata class, which would look something
> like this:
>
> class SomeClass
> {
> public:
> const int metadata_count = 2;
> //Partial-specialize this class for each property
> template<class Self, int N>
> struct metadata {};
>
> template<class Self>
> struct metadata<Self, 0>
> {
> Self& self;
> metadata(Self& self) : self(self)
> {}
>
> int get() const { ... }
> void set(int x) { ... }
> const char * name() { return "id"; }
> };
>
> template<class Self>
> struct metadata<Self, 1>
> {
> Self& self;
> metadata(Self& self) : self(self)
> {}
>
> string get() const { ... }
> void set(string x) { ... }
> const char * name() { return "name"; }
> };
> ...
> };
>
> Then I use the for_each from the MPL library to iterator over metadata classes.
> Then the user can access the properties using the visitor pattern like this:
>
> struct property_visitor
> {
> void operator(T x)
> {
> cout<< x.name()<< ","<< x.get();
> }
> };
>
> SomeClass x;
> visit_each(x, property_visitor());
All right so you still need the switch regardless in this case if you
want to implement a property(i) function.
i.e.
switch(i)
{
case 0:
return metadata<Self, 0>(self).get();
case 1:
return metadata>self, 1>(self).get();
...
}
>
> Now, the metadata_count is known because its all in one macro. To
> seperate it to each macro would require using the line number or
> something like that as the index. Which would require me to iterate
> over all integers to find valid metadata.
You could use __COUNTER__ to deal with this, but that's not very
portable, and might also prevent other uses of __COUNTER__ between
properties.
There are template-based techniques to have counters as well, but
they're quite tricky and tend to be fragile with subpar compilers.