2016-12-24 1 views
0

나는 Fortran에서 C++ (11/14)의 함수 reshape을 구현하려고하는데, 함수를 설계했다. 이 함수는 두 개의 std::initializer_list을 허용합니다. 첫 번째 initializer_listD 차원 배열을 초기화하는 데 사용하는 초기 값을 제공합니다. 두 번째 initializer_list은 배열의 각 차원 크기를 제공합니다. 나는이컴파일 타임에`std :: initializer_list`의 크기를 얻는다.

template<int D, typename T> 
auto forreshape(const std::initializer_list<T> & values, const std::initializer_list<int> & shape) 
{ 
    // some irrelevant codes to calculate lbound 
    return for1array_gen<T, D>(lbound, shape, values); // returns D dimension array fornarray<T, D> 
} 
int main(){ 
    auto reshaped_array = forreshape<2>({1, 2, 3, 4, 5, 6}, {2, 3}); 
} 

비 타입 템플릿 매개 변수 int D에게 주어진이 필요합니다이 구현 같은 초안을 작성,하지만 난 forreshape({1, 2, 3, 4, 5, 6}, {2, 3});처럼 D없이 무언가를 원한다. 처음에 std::initializer_list<T>::size을 사용하고 싶지만, static-assert-on-initializer-listsize에서 작동하지 않습니다. 주변을 보니 나는 how-to-cause-a-compile-time-error-based-on-the-size-of-an-initializer-list을 찾았지만 제 경우에는 도움이되지 않았습니다. 필자는 컴파일러가 충분한 정보를 얻고 int D automaticlly의 값을 추론 할 수 있다고 생각했지만 어떻게해야할지 모르겠다. 어쩌면 std::initializer_list을 사용하는 것이 좋지 않을까요? 나는 완전히 여기에서 길을 잃었다.

+3

'표준 : initializer_list <> :: 크기는()'C++ 14 constexpr''이다. 뭐가 문제 야..? – ildjarn

+0

컴파일 할 때 MSVC 2015를 사용하고 오류 C2131이 발생했습니다. – calvin

+0

MSVC 2015는 C++ 14 'constexpr'을 지원하지 않습니다 (MSVC 2017). 컴파일러에 대한 C++ 11 답변이 필요합니다. – ildjarn

답변

3

std::initializer_list를 사용하는 것은 나쁘지 않을까?

나는 그렇게 생각합니다. 위의 예에서

std::initializer_list<int> t; 
std::initializer_list<int> a = {1,2,3}; 
std::initializer_list<int> b = {2,3}; 
if (rand() > 42) 
    t = a; 
else 
    t = b; 
auto reshaped_array = forreshape({1,2,3,4,5,6}, t); 

고려,이 컴파일시에 t.size()을 알고 그냥 불가능합니다.

그러나 C 스타일 배열에 대한 참조를 사용하여 이니셜 라이저 목록의 길이를 추측하도록 컴파일러에 요청할 수 있습니다 (CWG 1591).

forreshape의 정의는 같을 것이다

template<int D, typename T> 
auto forreshape(const std::initializer_list<T> & values, const int (&shape)[D]) 
{ 
    // use D... 
} 
관련 문제