Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a template arguments

Tags:

c++

c++11

c++14

I am trying to pass a function as an argument to a template class - the objective is that then I can pass any function as a argument and achieve different functionality:

int A() 
{ 
return 0; 
}

void Test() {
    auto B2 = B<int(*A)()>(&A);
}

int main()
{
Test();
}

But I am getting compilation issue:

$ c++ -std=c++14 try.cpp
try.cpp: In function 'void Test()':
error: cast from 'int (*)()' to 'int' loses precision [-fpermissive]
     auto B2 = B<int(*A)()>(&A);
                       ^                       ^

How can I instantiate class B with a function of any return type and accepting any argument and resolve the compilation?

like image 647
Programmer Avatar asked Sep 23 '26 21:09

Programmer


1 Answers

You should remove the function name A in the template parameter in the line auto B2 = ... such that it looks like this:

auto B2 = B<int(*)()>(A);

The name is not a part of the type specifier, and the type is the only thing the compiler looks for when trying to instantiate the class template. You can use this snippet to refer to the name of the function and let the compiler deduce its type:

auto B2 = B<decltype(&A)>(A);

Note that you can optionally drop the & before A when passing it to the constructor of B (doesn't work for decltype(&A) though), as it's implicitly converted to a function pointer.

like image 126
lubgr Avatar answered Sep 25 '26 09:09

lubgr