Annoyance with function template unwrapping
Basile B.
b2.temp at gmx.com
Sat Jan 16 23:19:41 UTC 2021
On Saturday, 16 January 2021 at 22:09:48 UTC, solidstate1991
wrote:
> In one of my projects, I want to use function pointers that I
> get from a function template that has overloads. Easily
> reproducable example:
>
> void func(ubyte b)(int i)
> {
> writeln(__PRETTY_FUNCTION__);
> }
>
> void func(ubyte b)(float f)
> {
> writeln(__PRETTY_FUNCTION__);
> }
> void main()
> {
> void function(float) fp = &func!(5); // Error: template
> onlineapp.func matches more than one template declaration
> }
>
> However defining the function templates this way works:
>
> template func(ubyte b) {
> void func(int i) {
> writeln(__PRETTY_FUNCTION__);
> }
> void func(float i) {
> writeln(__PRETTY_FUNCTION__);
> }
> }
>
> I might change my project CPUblit to fit to the latter, and
> then add unittests to ensure that it works, but I don't know
> whether it's a bug, some odd behavior, or something DIP-worthy.
It's not a bug. If you rewrite the function without the shorthand
syntax then you realize that the error message is correct,
there's indeed two "template func(){}". As a workaround,
you can build the overlaod set explicitly, e.g
void func1(ubyte b)(float f) { }
void func2(ubyte b)(int i) { }
alias func = func1!5;
alias func = func2!5;
or the same but "meta-programmatically"
void f(ubyte b)(float f) { }
void f(ubyte b)(int i) { }
static foreach (o; __traits(getOverloads, mixin(__MODULE__),
"func", true))
alias func = o!5;
which allows to use a single ident for all the template func,
although the overload set must be named differently.
More information about the Digitalmars-d
mailing list