c++11 - static variables by instances

can i have 1 static variable with instance diferent value?
That would be an ordinary non-static member variable ;)
The difference is that a non-static member variable has class scope but the OP is asking for it to have function scope. It's an arbitrary restriction just because it's extra work to add it to the language and the resulting benefit is very small.
Per instance state: internal state => non-static member variables
State shared among all instances of a class: per-class internal state =>static member variables
State shared among some (not all) instances of a class: external state => held as shared objects.

A, somewhat crude, incomplete, example:

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
51
52
53
54
55
56
57
#include <iostream>
#include <string>
#include <tuple>
#include <set>

struct character
{
    enum font { TIMES_ROMAN, HELVETICA, BASKERVILLE /*, ... */ };
    enum colour { BLACK, RED, GREEN, BLUE /* , ... */ };

    character( char c, font f = HELVETICA, int points = 12, colour clr = BLACK )
          : ch(c), display_properties( shared_data.emplace( f, points, clr ).first ) {}

    char what() const { return ch ; }

    std::string typeface() const
    {
        switch( display_properties->font() )
        {
            case TIMES_ROMAN : return "Times Roman" ;
            case HELVETICA : return "Helvetica" ;
            case BASKERVILLE: return "Baskerville" ;
            default: return "Unknown" ;
        }
    }

    // etc.

    private:

        struct shared_state : std::tuple< character::font, int, character::colour >
        {
            using base = std::tuple< character::font, int, character::colour > ;
            using base::base ;

            character::font font() const { return std::get<0>(*this) ; }
            int size() const { return std::get<1>(*this) ; }
            character::colour colour() const { return std::get<2>(*this) ; }
        };

        static std::set< shared_state > shared_data ;

        char ch = ' ' ; // per-instance, not shared
        
        // state shared among all instances having the same type face, size and colour.
        std::set< shared_state >::iterator display_properties ; 
};

std::set< character::shared_state > character::shared_data ;

int main()
{
    character text[] = { { 'H', character::TIMES_ROMAN  }, { 'e', character::BASKERVILLE }, { 'l' },
                         { 'l' }, { 'o' }, { '!', character::BASKERVILLE, 12, character::RED }  } ;

    for( character c : text ) std::cout << c.what() << " - " << c.typeface() << '\n' ;
}

Precursor to flyweight: http://sourcemaking.com/design_patterns/flyweight
Topic archived. No new replies allowed.