简体   繁体   中英

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM