0

There is a struct and a generator function for it

template<int Size>
struct Foo
{
    int buffer[Size];
};

template<int Size>
Foo<Size> generate(int Size)
{
      return Foo<Size>();
}

and it produces this error:

: error: declaration of 'int Size' shadows template parameter
8 |     Foo<Size> generate(int Size)

clearly, I can't use same name of integer template parameter as the function parameter to force it deduce the Foo template's parameter.

Is there a way to pick the template parameter like this:

auto foo = generate(32);

instead of this:

auto foo = generate<32>();

Here 32 is compile-time known so it could work if there was a way to do it and I don't expect it to work like this:

auto foo = generate(clock()); // not known, so won't work

On the other hand, it could be good if it could auto-generate it for a limited range like this:

auto foo = generate(clock()%10); // compile-time known to be between 0 and 9

because it is not possible to do it like this:

auto foo = generate<clock()%10>();
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
  • I don't understand the `clock` part. If it's not `constexpr` what does it have to do with anything about the previous stuff? – Passer By Apr 24 '22 at 11:04
  • It's just an example of "compile-time-known" pattern. Modulus absolutely narrows the possibilities down to just 10 but compiler can not specialize them in compile-time. Similar to writing ```generate<1>()``` myself but prefer ```generate(1)``` if it is possible. Possible? – huseyin tugrul buyukisik Apr 24 '22 at 11:49
  • 1
    But there being 10 or 100 possible values has nothing to do with `Foo`. It behaves in the same way regardless. – Passer By Apr 24 '22 at 12:11
  • Having something like `Foo generate(int Size)` work means that the return type depends on the value you pass to `generate`. I can't see that fitting into the C++ type system: what would be the type of such a function? `Foo> (int)` ? – paolo Apr 24 '22 at 12:37
  • The struct will have a plain array inside. Plain arrays require compile-time constant size. That can't be passed from parameters right? – huseyin tugrul buyukisik Apr 24 '22 at 12:43
  • I believe not because of my previous comment. It's not clear to me why you'd want that: if you have a compile-time constant integer, why not call `generate`? – paolo Apr 24 '22 at 12:49
  • Related: [Will consteval functions allow template parameters dependent on function arguments?](https://stackoverflow.com/q/56130792/7143595) – MatG Apr 24 '22 at 19:14
  • So, there wont be integer deduction from function parameter ever. Ty. – huseyin tugrul buyukisik Apr 24 '22 at 19:29

0 Answers0