Search code examples
c++variadic-templatesvariadic-functionsc++20

Template type paremeter not expanding as desired


I was experimenting on c++ TMP when I noticed how powerful templates can be. But at some point I wondered why is the following code invalid yet it uses variadic template type expansion(1). When non-type variadic expansion works fine(2). The diviation doesn't make sense as in both the expanded parameters will not be usable. Or is it a problem with my compiler. clang++ std=c++20

  • Tests
    template<typename Y> struct Exp{
        static const bool useless=false;
    };
    template<typename... T> auto initAll1(int forAll,T...ts){
        std::array a={(ts,forAll)...};
    }
    template<typename... T> auto initAll2(int forAll){
        std::array a={(T,forAll)...};
    }
    template<typename... T> auto initAll3(int forAll){
        std::array a={(Exp<T>::useless,forAll)...};
        return a;
    }
    

    I am talking about initAll2. It is not working, I made initAll3 to avoid the error.


  • Solution

  • As max66's comment said, option 3 likely won't have any runtime overhead. But you could do this if you wanted something cleaner:

    template<typename... T>
    auto initAll2(int forAll){
        std::array a={std::conditional_t<true, int, T>{ forAll }...};
    }