1

I have a problem similar to

Generating a sequence of zeros at compile time

However, in my case I have no pack to expand. The situation is like this:

template<size_t N>
void foo()
{ bar(T{}, ..., static_cast<T>(1)); }

There are N - 1 T{}:s followed by a one.

It may happen that T is not usable as a non-type template parameter. There are two differences compared to the linked post

  1. In the linked post, there is already a parameter pack to rely on
  2. In the linked post, it is assumed that all arguments are integers

I may use a solution that require C++20

user877329
  • 6,717
  • 8
  • 46
  • 88
  • 1
    The "problem" you present to us and ask for help with is a *solution* to an (for us) unknown problem. What is that original and underlying problem you need to solve? Why do you think the proposed solution would solve it? Why don't you ask about the underlying problem directly instead, and present your solution as a possible way to solve it? It will help us write better and more context-aware answers, and maybe even come up with other possible solutions to your problem. In sort: This is very much an [XY problem](https://xyproblem.info/). – Some programmer dude Oct 08 '22 at 14:30
  • `T{}` is not null value – apple apple Oct 08 '22 at 15:11
  • @appleapple There is no generic "null" value in C++, but T{} is a good approximation. Arithmetic types set to zero (neutral under addition), pointers set to nullptr (the "origin" in address space), etc. It would be nice to have a generalized null concept similar to std::hash. – user877329 Oct 08 '22 at 18:36

2 Answers2

2

you generate the sequence yourself

#include <utility>
template<std::size_t N>
void foo(){
    [&]<std::size_t...I>(std::index_sequence<I...>){  
        bar((I,T{}) ... , static_cast<T>(1)); 
    }(std::make_index_sequence<N-1>());
}
apple apple
  • 10,292
  • 2
  • 16
  • 36
0

You can turn N into std::index_sequence<0, .., N-1> with std::make_index_sequence, then you might expand your pack as you want:

template<size_t N>
void foo()
{
    []<std::size_t...Is>(std::index_sequence<Is...>){
        bar(T{(static_cast<void>(Is), 0)}..., static_cast<T>(1));
    } (std::make_index_sequence<N - 1>());
}

Demo

template lambda is C++20, if you cannot use it, you have to make a similar template helper function.

Jarod42
  • 203,559
  • 14
  • 181
  • 302