C++ pointer to function declaration syntax - c++

What is the difference between the two declarations in case of foo's arguments? The syntax in the second one is familiar to me and declares a pointer to function. Are both declarations fully equivalent?
void foo(int(int));
void foo(int(*)(int));

They are equivalent as long as int(int) and int(*)(int) are used in function parameter lists. In function parameter list the int(int) is automatically adjusted by the language to mean int(*)(int).
It is the same adjustment mechanism that makes int [] parameter declaration equivalent to int * parameter declaration.
Outside of this specific context int(int) and int(*)(int) mean two different things.

Related

Why is 'void' used and not a specific data type as argument for a function in C++ using a class object array? [duplicate]

Consider these two function definitions:
void foo() { }
void foo(void) { }
Is there any difference between these two? If not, why is the void argument there? Aesthetic reasons?
In C:
void foo() means "a function foo taking an unspecified number of arguments of unspecified type"
void foo(void) means "a function foo taking no arguments"
In C++:
void foo() means "a function foo taking no arguments"
void foo(void) means "a function foo taking no arguments"
By writing foo(void), therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an extern "C" if we're compiling C++).
I realize your question pertains to C++, but when it comes to C the answer can be found in K&R, pages 72-73:
Furthermore, if a function declaration does not include arguments, as
in
double atof();
that too is taken to mean that nothing is to be assumed about the
arguments of atof; all parameter checking is turned off. This special
meaning of the empty argument list is intended to permit older C
programs to compile with new compilers. But it's a bad idea to use it
with new programs. If the function takes arguments, declare them; if
it takes no arguments, use void.
C++11 N3337 standard draft
There is no difference.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
Annex C "Compatibility" C.1.7 Clause 8: declarators says:
8.3.5 Change: In C ++ , a function declared with an empty parameter list takes no arguments. In C, an empty
parameter list means that the number and type of the function arguments are unknown.
Example:
int f();
// means int f(void) in C ++
// int f( unknown ) in C
Rationale: This is to avoid erroneous function calls (i.e., function calls with the wrong number or type of
arguments).
Effect on original feature: Change to semantics of well-defined feature. This feature was marked as “obsolescent” in C.
8.5.3 functions says:
4. The parameter-declaration-clause determines the arguments that can be specified, and their processing, when
the function is called. [...] If the parameter-declaration-clause is empty, the function
takes no arguments. The parameter list (void) is equivalent to the empty parameter list.
C99
As mentioned by C++11, int f() specifies nothing about the arguments, and is obsolescent.
It can either lead to working code or UB.
I have interpreted the C99 standard in detail at: https://stackoverflow.com/a/36292431/895245
In C, you use a void in an empty function reference so that the compiler has a prototype, and that prototype has "no arguments". In C++, you don't have to tell the compiler that you have a prototype because you can't leave out the prototype.

`f(void)` meaning no parameters in C++11 or C?

In C++11 the following function declaration:
int f(void);
means the same as:
int f();
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
I get the (perhaps false) impression this is an old feature, perhaps inherited from C?
Does anyone know the history or rationale behind this way to declare a function with no parameters?
In C++ they both mean the same thing.
In C f(void) is different from f(), becuse f() means "unspecified parameters" - you can legally pass anything (whether the function at receiving the data is happy about that or not is another matter).
In C++ both are the same thing.
In C, f() means that we don't know how many parameters the function takes at this point. It is unspecified parameters. And f(void) means that this function does not take any parameters.
From the C standard :
6.7.6.3 Function declarators (including prototypes)
6/ A parameter type list specifies the types of, and may declare identifiers for, the
parameters of the function.
10/ The special case of an unnamed parameter of type void as the only item in the list
specifies that the function has no parameters.
14/ An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.
And like you said, in the C++ standard :
8.3.5 Functions [dcl.fct]
4/ The parameter-declaration-clause determines the arguments that can be specified, and their processing, when the function is called. [ Note: *the parameter-declaration-clause* is used to convert the arguments specified on the function call; see 5.2.2. —end note ] If the parameter-declaration-clause is empty, the function takes no arguments. A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
This comes to C++ from C. In C f() means unknown number and type of parameters. So in C for no parameters there is f( void ).
In C++ it's redundant: f() and f( void ) mean same thing - a function that has no parameters.
From "A History of C++" (1979− 1991 by Bjarne Stroustrup) at p11:
C with Classes introduced the notation f(void) for a function f that
takes no arguments as a contrast to f() that in C declares a function
that can take any number of arguments of any type without any type
check.
It says later, however, that soon the empty function declarator was given its obvious meaning and the new construct - kinda rendered obsolete for the time. I guess nobody has bothered removing it after (or maybe there had been already some C++ code written with it that have needed support).
In C:
This construct however rendered important role as of the standardization of the C language where function prototyping was borrowed directly from C++. In this case f(void) was useful in supporting existing C code (in which the notion f() was already reserved as to indicate a function taking unspecified number of arguments).
Before that the C language hadn't been able to attach specific types to each parameter but only functions with unspecified number of arguments and with unspecified types were declarable using the f() form.
In C++, there is no difference. However, this is inherited from C, where int f() mean "function which can take any number of arguments of any types" and int f(void); specifies functions that takes no arguments.
Edit As Angew pointed out, in C, f() means "function whose parameters are unknown at this point." It does not mean it can take any number of arguments - close to that would be f(T arg, ...), where arg is at least one named parameter before ..., which accepts at least one argument, arg (as pointed by #hvd).

Function with default parameter as template type

I am trying to use a function with a default argument as a function pointer template parameter:
template <void (*F)()>
class A {};
void foo1(int a = 0) {}
void foo2() {}
int main()
{
//A<foo1> a1; <-- doesn't work
A<foo2> a2;
}
The compiler error is:
main.cpp:7:7: error: could not convert template argument ‘foo1’ to ‘void (*)()’
Is there specific syntax for this to work? Or a specific language limitation? Otherwise, the alternative is to have two separate functions instead of a default parameter:
void foo1(int a) {}
void foo1() { foo1(0); }
Update
I understand that the signatures are different, but I'm wondering if there is a way to make this work conveniently without needing to modify all the functions with default parameters?
The signature of foo1 is void(int), not void(). This is why it isn't convertible to void(*)().
You are confusing default arguments with overloading.
According to section 8.3.6 of the C++ standard,
If an expression is specified in a parameter declaration this expression is used as a default argument. Default arguments will be used in calls where trailing arguments are missing.
Since A<foo1> is not a call of the function, default arguments are ignored. In fact, they are ignored in all contexts except the calls of the function, for example
typedef void (*FFF)();
FFF x = foo1;
will not compile, and produce the same message that you get when trying to use foo1 as a template parameter:
error: invalid conversion from ‘void (*)(int)’ to ‘void (*)()’
This makes sense, because evaluating default arguments is a separate step in the invocation:
8.3.6.9: Default arguments will be evaluated each time the function is called.
The presence of default arguments does not alter the signature of your function. For example, you cannot use a single-argument function with a default argument to override a no-argument virtual member function.
Default argument values are not part of the function type. You can't use foo1 as a function taking no arguments, because it does take one argument. The argument gets filled in for you if you don't mention it, but it's still there.
Your workaround involving a dispatching function sounds like a good solution. It could even be templated if you need it a lot.
I'm pretty sure that a function pointer has signature of the function with all default parameters expanded and function pointers cannot convert to a function pointer with a different signature. Finding this in the standard is a different matter, though...
I think the relevant clause from the standard is 8.3.5 [dcl.fct] paragraph 6:
... The return type, the parameter-type-list, the ref-qualifier, and the cv-qualifier-seq, but not the default arguments (8.3.6) or the exception specification (15.4), are part of the function type. [ Note: Function types are checked during the assignments and initializations of pointers to functions, references to functions, and pointers to member functions. —end note ]
Note that default arguments are the guys of the form = value according to 8.3.6 [dcl.fct.default] paragraph 1:
If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a default argument. ...
It won't compile because foo1 has signature:
void foo1(int a);
which you're trying to stick into a pointer to:
void F()
The function signatures don't match. The fact that foo1 has a default parameter doesn't change the function's signature (it still can take in an int).
A More Generic Solution
I'd say forget about the templates, they're only limiting you here.
Personally, the way I solve the callback problem is using function objects with argument binding. It can be done using the boost::function library, and binding default arguments with boost::bind (or std::bind1st and std::bind2nd).
These boost libraries are also built-in to the new C++11 standard, as std::function, and std::bind.
It's well worth taking a look at this, as it let's you do some very nice things, like providing default arguments to functions, or use class member functions as callbacks.
The sites I've linked to all have lots of example code, and the boost links have tutorials.

what is the difference between function declaration and signature?

In C or C++ what is the difference between function declaration and function signature?
I know something of function declaration but function signature is totally new to me. What is the point of having the concept of function signature? What are the two concepts used for actually?
Thanks!
A function declaration is the prototype for a function (or it can come from the function definition if no prototype has been seen by the compiler at that point) - it includes the return type, the name of the function and the types of the parameters (optionally in C).
A function signature is the parts of the function declaration that the compiler uses to perform overload resolution. Since multiple functions might have the same name (ie., they're overloaded), the compiler needs a way to determine which of several possible functions with a particular name a function call should resolve to. The signature is what the compiler considers in that overload resolution. Specifically, the standard defines 'signature' as:
the information about a function that participates in overload resolution: the types of its parameters and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared.
Note that the return type is not part of the function signature. As the standard says in a footnote, "Function signatures do not include return type, because that does not participate in overload resolution".
The standard defines two terms: declaration and definition. A definition is a tentative declaration. However, the C99 and C++03 standards have slightly varying definitions.
From C++0x draft:
Appendix C
8.3.5 Change: In C++, a function declared
with an empty parameter list takes no
arguments. In C, an empty parameter
list means that the number and type of
the function arguments are unknown"
Definitions
1.3.11 signature
the name and the parameter-type-list
(8.3.5) of a function, as well as the
class, concept, concept map, or
namespace of which it is a member. If
a function or function template is a
class member its signature
additionally includes the
cv-qualifiers (if any) and the
ref-qualifier (if any) on the function
or function template itself. The
signature of a constrained member
(9.2) includes its template
requirements. The signature of a
function template additionally
includes its return type, its template
parameter list, and its template
requirements (if any). The signature
of a function template specialization
includes the signature of the template
of which it is a specialization and
its template arguments (whether
explicitly specified or deduced). [
Note: Signatures are used as a basis
for name mangling and linking.—end
note ]
The function signature doesn't include the return type or linkage type of the function.
OK, Wikipedia disagrees with me on the return type being included. However I know that the return type is not used by the compiler when deciding if a function call matches the signature. This previous StackOverflow question appears to agree: Is the return type part of the function signature?
Also please note that top-level const and volatile on argument are not part of the signature, according to the standard. But some compilers get this wrong.
e.g.
void f(const int, const char* const);
has the same signature as
void f(int, const char*);
A function declaration is a prototype. A function signature indicates what is the return type and the parameters used that makes up the signature. Consider this:
int foo(int, int); /* Function Declaration */
/* Implementation of foo
** Function signature
*/
int foo(int a, int b){
}
Now, consider this scenario: a programmer is asked what is the function signature for foo:
It returns a datatype of int
Two parameters are also of datatype of int, named a and b respectively
The function prototype on the other hand is to clue in the C/C++ compiler, on what to expect and if the signature does not match up with the prototype, the compiler will emit an error, along the context of 'function declaration error' or 'prototype mismatch'.

How to prevent Overloading?

Is it possible to prevent overloading of user defined functions in C++? Suppose I have a function as:
void foo(int , int);
Can I prevent foo from being overloaded, and if so how? If I can, can this be extended to prevent overriding of the methods through inheritance?
In a word: no. You can't prevent an overload of foo being defined with a different signature somewhere else and you also can't prevent virtual functions from being overriden.
In the C++ world you have to give some degree of trust to people writing code that winds up in your program.
Section 13.1.1 through 13.1.3 of the standard describe the kinds of functions that can not be overloaded:
Certain function declarations cannot be overloaded:
Function declarations that differ only in the return type cannot be overloaded.
Member function declarations with the same name and the same parameter types cannot be overloaded if any of them is a static member function declaration (9.4).
Note: as specified in 8.3.5, function declarations that have equivalent parameter declarations declare the same function and therefore cannot be overloaded:
Parameter declarations that differ only in the use of equivalent typedef “types” are equivalent. A typedef is not a separate type, but only a synonym for another type (7.1.3).
Parameter declarations that differ only in a pointer * versus an array [] are equivalent. That is, the array declaration is adjusted to become a pointer declaration (8.3.5). Only the second and subsequent array dimensions are significant in parameter types (8.3.4).
Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).
Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.
Two parameter declarations that differ only in their default arguments are equivalent.
Otherwise, the function can be overloaded, and there is no way to prevent that.
You cannot.
Make it a static function in a class and tell people not to modify that class?
This can be simulated by making it a struct instance:
struct foo_t {
void operator()(int, int);
} foo;
// error: redefinition of 'foo' as different kind of symbol
void foo(double, double);
or a function reference:
void foo_impl(int, int);
auto const& foo = foo_impl;
// error: redefinition of 'foo' as different kind of symbol
void foo(double, double);
Do what UncleBens said, and include in the class a constant which is an encrypted checksum of the text in the class, and a function to test it for validity. That way, nobody can change the class. Just a thought (maybe not a very good one).
As I think about it, that's pretty dumb because the class would need its own text. However, as an alternative, it could read its compiled binary code, and have a checksum for that. I'm getting out on a limb here.
The only reasonable way would be to give the function C linkage:
extern "C" void foo(int , int);
This works because with C linkage, names aren't mangled, so you can't do any overloading (which relies on encoding the types of arguments into the symbol name).
Obviously this won't extend to member functions.