[英]How to declare a pointer to a function of return type X and input parameter A?
What is the general form of declaring a pointer to a function which, say is of return type X and accepts the input parameter &Y? 声明指向返回类型X并接受输入参数&Y的函数的指针的一般形式是什么?
is it: 是吗:
X my_function(Y &y){
//code
}
X (*my_pointer) (Y &y) = my_function;
? ?
X (*fptr)(Y&) = my_function;
Or: 要么:
auto fptr = my_function; // c++11
Or: 要么:
std::function<X(Y&)> fptr(my_function); // c++11, boost::function if not
What you wrote is OK, but you normally do not write the name of function arguments if you just want to declare a function pointer of that type: 所写的内容还可以,但是如果您只想声明该类型的函数指针,则通常不写函数参数的名称:
X (*my_pointer) (Y&) = my_function;
Depending on your taste, you may want to be more C++11-ish and write: 根据您的喜好,您可能想要更多的C ++ 11风格并编写:
#include <type_traits>
std::add_pointer<X(Y&)>::type my_pointer = my_function;
It can get even more readable with a template alias: 使用模板别名可以使其更具可读性:
#include <type_traits>
template<typename T>
using AddPointer = typename std::add_pointer<T>::type;
AddPointer<X(Y&)> my_pointer = my_function;
Or even use auto
and forget about naming the function type explicitly, as suggested by hmjd in his answer . 甚至使用
auto
, 而不必像hmjd在他的答案中建议的那样显式命名函数类型。 If you would later need to retrieve the type, you could do: 如果以后需要检索类型,则可以执行以下操作:
decltype(my_pointer)
is it: 是吗:
X my_function(Y &y){ //code } X (*my_pointer) (Y &y) = my_function;
? ?
Yes 是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.