Programmer
Programmer

Reputation: 8687

Passing a function as a template arguments

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?

Upvotes: 3

Views: 193

Answers (2)

lubgr
lubgr

Reputation: 38267

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.

Upvotes: 4

llllllllll
llllllllll

Reputation: 16404

Function name is not part of the type of a function pointer.

This line:

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

should be:

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

Upvotes: 2

Related Questions