9

With the upcoming C++17 feature of non-type template arguments with auto, will it be possible to implement std::function in such a way as to be able to put, for example, the following functions:

    bool f(int n,  double d) {}    
    bool g(bool b, char c)   {}
    bool h(bool b)           {}

into auto-templated std::function objects:

   std::function<bool(auto,   auto)> faa = f; // ok
   std::function<bool(int,    auto)> fia = f; // ok
   std::function<bool(double, auto)> fda = f; // error: function type mismatch
   std::function<bool(auto,   auto)> gaa = g; // ok
   std::function<bool(auto,   auto)> haa = h; // error: function type mismatch
   std::function<bool(auto)>         ha  = h; // ok

And so on.

In other words, to have std::function objects constrained on the function types they accept?

(Currently, on GCC we get an error: 'auto' parameter not permitted in this context.)

Davit Tevanian
  • 861
  • 8
  • 16

1 Answers1

7

Those are not non-type template arguments, so auto is not permitted there in C++17.

Non-type template arguments are arguments to templates that are pointers or integers or similar, actual values, not types.

For an example,

std::integral_constant<std::size_t, 7>;

here the 7 is a non-type template argument of type std::size_t and value 7.

Non-type template auto permits something like:

template<auto x>
using integral = std::integral_constant< decltype(x), x >;

now integral<7> is std::integral_constant<int, 7>.

On the other hand, your use of auto is in place of a type, not a non-type.


There is a feature where the type of the template is deduced, so you could write:

std::function faa = f;

if they augmented std::function to be able to deduce a signature from a function pointer (or non-template callable).

Note however that this std::function would have a fixed signature, not a template one. The feature simply allows deduction, not template dynamic dispatch.

I don't know if std::function was augmented in this way in C++17, but the language feature to do so was added.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • *"template dynamic dispatch"* oh lord... I hope that this thing never exists – Guillaume Racicot Sep 27 '16 at 15:29
  • @GuillaumeRacicot Simply ship a compiler, an abstraction of source, and require the caller provide the same for the template arguments passed in. Compile it and memoize the compilation during dispatch. Easy-peasy! Scripting/bytecode languages do it all the time (usually with less power than C++ templates). – Yakk - Adam Nevraumont Sep 27 '16 at 15:48