4

I have a template which looks something like this:

template< typename T, void (*f)( T& param )>
class SomeAction
{
...
};

f is used inside SomeAction (actually f is a class member, but I don't think it's matter).

Question is: can this be improved by removing 'typename T' from template parameters list and let compiler to deduce that type?

Thanks!

T.C.
  • 133,968
  • 17
  • 288
  • 421
Leo
  • 131
  • 1
  • 9

1 Answers1

3

Perhaps the C++17 feature you are looking for is Declaring non-type template parameters with auto

I can't test this yet because there is no compiler that support this feature yet, but presumably it would allow you to write a partial specialization of SomeAction that would deduce T

template<auto> class SomeAction;
template<void (*f)(auto&)> class SomeAction<f> {};

void foo(int&) { /* bla */ }

int main()
{
    // C++17 only, no compiler support yet
    SomeAction<f> s; // T deduced to be int
}
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • 3
    I think [template](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0127r2.html) is more relevant. – cpplearner Aug 10 '16 at 13:36
  • @cpplearner: I fail to see how, since you can't just stick that in a type. – Nicol Bolas Aug 10 '16 at 13:46
  • AFAIK In C++17 OP's code will be written as `template< auto > class SomeAction; template class SomeAction { ... };`. – cpplearner Aug 10 '16 at 13:54
  • @cpplearner updated, still not 100% sure that this will be possible, no way to test it yet – TemplateRex Aug 10 '16 at 14:04
  • I think this is invalid. The wording says that auto is valid as part of " and as a decl-specifier of the parameter-declaration's decl-specifier-seq in a template-parameter", it doesn't seem valid in the parameter type of the function (and unless they added the feature for c++17, `void (*f)(auto) = &foobar;` in local scope is just as invalid). It would seem to be valid if you said `auto (*f)()`, because there it's in the decl-specifier-seq of `f`. – Johannes Schaub - litb Aug 12 '16 at 17:39
  • However, it also says "When the value of the argument corresponding to a non-type template parameter P that is declared with a dependent type is deduced from an expression, the template parameters in the type of P are deduced from the type of the value.", so it I think that `template` should work, but not sure. – Johannes Schaub - litb Aug 12 '16 at 17:42