language: C++11 (gcc-4.7.2)
date: 373 days 7 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
#include<string>
#include<type_traits>
using std::string;
using std::cerr;
using std::endl;
 
// base trait class stores data we want to access & modify in a uniform manner at runtime
struct TraitBase{
        string _name, _label;
};
// template derived class stores data that are accessed at compile-time
template<int _flags>
struct Trait: public TraitBase{
        // saves compile-time flags for easy access
        enum{flags=_flags};
        // named parameter idiom; must be defined here (not in TraitBase) so that ref to ourselves is returned
        // in that way, chained expression retains template parameters
        Trait& name(const string& s){ _name=s; return *this; }
        Trait& label(const string& s){ _label=s; return *this; }
};
 
struct Foo{
        #define aTrait Trait<23>().name("a").label("[original label]")
        int a;
        static decltype(aTrait)& makeTrait_a(){
                // remove reference in case named parameters are used in aTrait
                static std::remove_reference<decltype(aTrait)>::type _a=aTrait;
                return _a;
        }
        // we need std::remove_reference for decltype (otherwise error with gcc 4.5)
        //
        // this typedef also works around limited support for decltype in gcc-4.5;
        // e.g. std::remove_reference<decltype(Foo::makeTrait_a())>::type::flags would fail
        typedef std::remove_reference<decltype(Foo::makeTrait_a())>::type TraitType_a;
};
 
template<int val> void printFlags(){ cerr<<"[compile-time flags "<<val<<"]\n"; }
 
int main(void){
        // show compile-time resolution
        printFlags<Foo::TraitType_a::flags>();
 
        // show that static initialization works
        cerr<<Foo::makeTrait_a()._name<<": "<<Foo::makeTrait_a()._label<<endl;
 
        // show that reference to the single object is passed around properly
        Foo::makeTrait_a().label("[changed label]");
        cerr<<Foo::makeTrait_a()._name<<": "<<Foo::makeTrait_a()._label<<endl;
}