0

I have a template which takes a function of some varying signature as an argument, and produces a related function of a simple signature. The details aren't terribly important, it's some kind of delegate. It looks roughly like this.

struct foo;

using desired_signature_t = int(*)(foo*);

template <typename F, F f>
struct make_delegate;

template <typename... Args, int(*target_func)(foo*, Args...)>
struct make_delegate<int(*)(foo*, Args...), target_func> {
   static int delegate(foo *) { ... }
};

To use it, what I currently do is:

#define MAKE_DELEGATE(f) &make_delegate<decltype(f), (f)>::delegate

int bar(foo *, int, float, double);

desired_signature_t delegated_bar = MAKE_DELEGATE(&bar);

I use a macro because, I don't like having to type the argument twice, once for decltype and once for the actual function pointer.

Is there a way to do this without typing it twice and also without using a macro? The issue is that the type of a non-type template parameter cannot be deduced, and I couldn't find a way to deduce those types first in an earlier template. I thought about trying to construct a literal object with a template constructor as a helper, but I'm not sure if that's helpful -- I still can't use the parameter to the ctor as a template parameter inside the ctor, and once I'm out of the ctor I don't know the function type anymore.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
  • Colud [this](http://stackoverflow.com/questions/37541787/create-a-stdfunction-type-with-limited-arguments) be of interest? – skypjack Jun 19 '16 at 20:52
  • 2
    Can you provide some details about how you intend to use `target_func` in the definition of `delegate` ? Also, it's always interesting to know what's the goal, as the solution might be entirely different. – Johan Boulé Jun 20 '16 at 02:02
  • @JohanBoule: The basic idea is that, `foo*` has access to the rest of the parameters that the function is expecting. The delegate is going to extract them if possible, and then call `target_func`. If it can't extract them, it signals an error. – Chris Beck Jun 22 '16 at 20:27
  • So I guess this is not a great question. What I'm hoping to find I guess is some generic way that I can work around `type of a non-type template parameter cannot be deduced`. But if there were a generic way to work around that, probably the restriction would not exist... sometimes in C++ there are arbitrary restrictions and generic workarounds for them, but not always, and in this case I guess it now seems more unlikely to me... – Chris Beck Jun 22 '16 at 20:29

1 Answers1

1

I think the answer is, use template <auto> in C++17, and until then, keep using the macro.

Advantages of auto in template parameters in C++17

Community
  • 1
  • 1
Chris Beck
  • 15,614
  • 4
  • 51
  • 87