With reference to the following code
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
void function() {
cout << "Hello World" << endl;
}
int main() {
vector<void (*) ()> functions;
functions.push_back(function); // (1) no error
functions.push_back(&function); // (2) no error
for (const auto& func : functions) {
func();
}
// vector<decltype(function)> vec; // (3) error
return 0;
}
There seems to be an error when I uncomment (3), I am just trying to understand the reasoning behind this. When I pass in a function as the argument to a templated function does it resolve the type to a function pointer? It would make sense for the compiler to deduce all function types as such to a function pointer but why then does the decltype() not resolve to a function pointer?
decltype(function)
is void()
- a function.
what you need is the decayed version of a function - void(*)()
:
std::decay<decltype(function)>::type
std::vector < std::decay<decltype(function)>::type > myPtrFunctionVec;
PS.
if you're working with VC++ (visual stdio) you can easily see the type deduced from decltype
by printing typeid(decltype(XXX)).name()
. VC++, unlike other compilers, gives the undecorated name of a type. very handy for metaprogramming debugging.
EDIT:
as @Daniel Jour has commented, the solution decltype(&function)
workd as well, because the construct &f
gives the pointer to f
, which is what you need
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.