I cite immediately the code for clarification:

struct S { S(int) {} }; int iArr[] = { 1, 2, 3 }; S sArr[] = { iArr[0], iArr[1], iArr[2] }; 

I want to avoid manually changing the initialization code of the sArr array when changing the number of values ​​in iArr . Interests exactly compile-time initialization.

Is it possible? If so, how?

The options are interesting for both c ++ 03 (probably macros are not enough), and a modern approach (most likely variadic-templates ). If something suitable is expected in the new Standard, then it would also be nice to see in the answers.

  • std::make_index_sequence<countof(iArr)> to help. - Abyx
  • Good question, but the set of tags is very unusual :) - Qwertiy
  • 3
    And why to the common language tag tags of all versions? We kind of agreed that the common language label applies to all versions ? Or did you want to exclude C ++ 98? : D Or did he just not get into the tags? - D-side
  • @D-side, for some reason, I was sure that with a bare tag, the latest available version would be implied. I will remove the surplus then. - αλεχολυτ

2 answers 2

C ++ 14 solution based on @Abyx code :

 #include <utility> #include <iostream> #include <array> struct S { constexpr S(int i) : i(i*i) { } int i; }; template<typename R, typename S, size_t... I> constexpr auto makeArrayHelper(const S(&src)[sizeof...(I)], std::index_sequence<I...> ) { return std::array<R, sizeof... (I)>{ { src[I]... } }; } template<typename R, typename S, size_t N> constexpr auto makeArray(const S(&src)[N]) { return makeArrayHelper<R>(src, std::make_index_sequence<N>()); } int main() { constexpr int iArr[] = { 1, 2, 3 }; constexpr auto sArr = makeArray<S>(iArr); for( auto& s : sArr ) { std::cout << si << "\n"; } } 

    Um, for C ++ 03 through #define - what is not an option

     #define INIT { 1, 6, 3, 7, 8, 9 } int iArr[] = INIT; S sArr[] = INIT; 

    ? :)

    • codepad.org/LHkKucFt - oh .. I was late with the answer to <s> 18 </ s> 9 minutes ... - Qwertiy
    • constexpr for c ++ 03? :) And so, of course, good. Easier steamed turnip turned out. - αλεχολυτ
    • @alexolut No, sorry, that's what I have left of the experiments ... - Harry
    • It looks not very compile-time'ovo (without constexpr) - Andrey Buran
    • one
      @AndreyBuran is not only on main , but on __static_initialization_and_destruction_0 . The call to constructors S will be at runtime, yes. - αλεχολυτ