C++标准中函数指针是否被认定为函数对象?
Great question—let’s break this down using the C++ standard definition you cited, plus concrete examples to clarify.
First, let’s restate the standard’s definition clearly:
函数对象类型是可作为函数调用中后缀表达式类型的对象类型。
To unpack this, a type needs two key traits to qualify as a function object type:
- The type must be an object type (meaning
std::is_object_v<T>returnstruefor it) - Instances of the type can be used as the target of a function call expression (i.e., you can write
instance(args...)and have it compile and run validly)
Now let’s verify function pointers against these criteria:
- Function pointers are object types: As you observed, for any function pointer type
P,std::is_object_v<P>evaluates totrue. Function pointers are scalar types, which fall under the official C++ definition of object types. - Function pointers support function call syntax: You can absolutely invoke a function pointer using the
ptr(Args...)syntax, just like a regular function or a custom functor. Here’s a quick example:void greet(const std::string& name) { std::cout << "Hello, " << name << "!\n"; } // Define a function pointer type and assign it using GreetFunc = void(*)(const std::string&); GreetFunc greet_ptr = greet; // Call via the pointer—works exactly like calling the function directly greet_ptr("Alice");
So to wrap it up: yes, function pointers are considered function objects under the C++ standard definition.
It’s totally normal to initially associate "function objects" only with functors (custom class types that overload operator()), since those are the most commonly taught and used form in everyday code. But the standard’s definition is intentionally broader—it covers any object type that can be called like a function, and function pointers fit that description perfectly.
内容的提问来源于stack exchange,提问作者Vincent

