Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deduce template parameter for a template function pointer with default template parameter

Though the question seems a little bit confusing. The code is simple as:

template <typename T>
void tfunc(T&& getter)
{

}

template <typename T = void>
void voidfunc()
{}

int main() {
    tfunc(&voidfunc);   // error: could not deduce template argument for 'T'
    tfunc(&voidfunc<int>); // ok
    voidfunc(); // calling using default template parameter is ok.
}

Both clang 11& msvc visual studio 2019 16.7 complains error. Why I need to explicitly specify a template argument?

Background

  • the argument is a dummy parameter just to delay the instantiation of voidfunc to where it is used. The type doesn't really matter.
  • &voidfunc is used by some code generated by clangAST, otherwise I need to tweak the generator to write &voidfuc<> if it is a template.
  • __declspec(property(put=voidfunc)) this clang/msvc extension however takes voidfunc but not voidfunc<>

I've tweaked the generator to output &voidfunc<> as @Jarod42 says, if the given function is a template. And it works for now.

like image 468
Joey.Z Avatar asked Sep 02 '21 13:09

Joey.Z


People also ask

Can template parameters have default values?

Just like in case of the function arguments, template parameters can have their default values. All template parameters with a default value have to be declared at the end of the template parameter list.

What is template argument deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

Which is a correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.


1 Answers

As stated in the comments, this situation was not clear in the standard until C++20, where it was cleaned up in order to better support the new feature of constrained functions. The new specification makes sense in previous language versions (ignoring the possibility of constraints), so hopefully implementations will eventually support this usage everywhere.

like image 60
Davis Herring Avatar answered Oct 19 '22 13:10

Davis Herring