Is it possible to create and initialize an array of values using template metaprogramming?

前端 未结 7 757
悲&欢浪女
悲&欢浪女 2020-12-04 22:20

I want to be able to create an array of calculated values (let\'s say for simplicity\'s sake that I want each value to be the square of it\'s index) at compile time using t

7条回答
  •  误落风尘
    2020-12-04 22:50

    You can have that for fixed-size arrays:

    int a[] = { foo<0>::value, foo<1>::value, ... };
    

    Arbitrarily sized arrays however can't be done without preprocessor meta-programming - Boost.Preprocessor can help here.

    Another thing you might want to look into are compile-time sequences of integral constants, e.g. using Boost.MPL:

    template
    struct squares {
        typedef typename squares::type seq;
        typedef typename boost::mpl::integral_c::type val;    
        typedef typename boost::mpl::push_back::type type;
    };
    
    template<>
    struct squares<1> {
        typedef boost::mpl::vector_c::type type;
    };
    
    // ...
    typedef squares<3>::type sqr;
    std::cout << boost::mpl::at_c::type::value << std::endl; // 1
    std::cout << boost::mpl::at_c::type::value << std::endl; // 4
    std::cout << boost::mpl::at_c::type::value << std::endl; // 9
    

    (Note that this could probably be done more elegantly using MPLs algorithms)

    If you're more curious about the compile-time subject the books "Modern C++ Design" (TMP basics) and "C++ Template Metaprogramming" (mainly MPL explained in depth) are worth looking into.

提交回复
热议问题