简体   繁体   English

如何声明一个指向返回类型X和输入参数A的函数的指针?

[英]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.

相关问题 基于输入类型参数C++返回函数指针 - Return function pointer based on input type parameter C++ 如何声明一个函数返回一个指向函数的指针返回一个指向int [3]的指针 - How to declare a function return a pointer to function return pointer to int[3] 如何声明/定义一个 function 与给定的 function 指针具有相同的返回和参数类型? - How to declare/define a function with the same return and parameter types as a given function pointer? 如何将指针作为函数参数返回 - How to return a pointer as a function parameter 如何声明指向其返回类型取决于模板类的模板函数的函数指针 - How to declare a function pointer to a template function whose return type is dependent on template class 是否可以声明指向具有未知(在编译时)返回类型的函数的指针 - Is it possible to declare a pointer to a function with unknown (at compile time) return type decltype声明函数返回类型的参数(不带auto) - decltype to declare parameter of return type of a function (without auto) 如何在C ++中将指向变量的指针声明为函数的参数? - How to declare a pointer to a variable as a parameter of a function in C++? 如何返回 function 的指针并用作参数? - How to return a pointer of a function and using as a parameter? 指针返回类型的函数 - Function with pointer return type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM