2012-12-31 2 views
3

나는 n이 아래 enum에서 Last의 값에 따라 컴파일 타임에 알려진 곳 {0, 1, 2, 3, ..., n}에 클래스 Foo에서 static const std::vector을 initalize 싶습니다. 목표는 Foo::allFruit 열거 형의 모든 값을 포함시키는 것입니다.C는 동적으로

foo.h에서 :

enum Fruit { Apple, Orange, Banana, ..., Last }; 

class Foo { 
public: 
    static const vector<int> all; 
}; 

foo.cpp에서 :

// initialization of Foo::all goes here. 

답변

4

당신은 boost::irange 사용할 수 있습니다

auto range = boost::irange(0, n + 1); 
const vector<int> Foo::numbers(range.begin(), range.end()); 
2

경우 n가 충분히 작은 당신이 c++0x 또는 c++11을 지원하는 컴파일러를 사용, 단지

const std::vector<int> Foo::all{0, 1, 2, 3, ..., n}; 
밖으로 철자

@ Jonathan의 설명에 따라 수정되었습니다.

+0

은'='기호를 사용하지 것이다 관용적 C++ (11)의 방법을 사용하여 constexpr 기능을 만들 수 있습니다. –

+0

@JonathanWakely, 'BigInt i = 5'및 BigInt i (5);와 같은 거래와는 다른 점이 있습니까? – chris

+0

@JonathanWakely 알았어, 나는 그걸 몰랐다. g ++는 둘 중 하나를 허용합니다. –

6

을 세 번째 옵션으로 :

namespace { 
    std::vector<int> create(); 
} 
const std::vector<int> Foo::all = create(); 

그리고 create()도 각 요소에 대해 push_back()를 사용하여, 그것을 좋아하는 무엇이든 할 수는 ISN를 생성 vector 때문에 ' t const.

또는 당신은 create()에게 <index_tuple.h>

#include <redi/index_tuple.h> 

namespace { 
    template<unsigned... I> 
    constexpr std::initializer_list<int> 
    create(redi::index_tuple<I...>) 
    { 
     return { I... }; 
    } 
} 

const std::vector<int> Foo::all = create(typename redi::make_index_tuple<Last>::type());