c++11 - Multiple declarations of C++ functions with default parameters -
c++11 - Multiple declarations of C++ functions with default parameters -
i utilize typedefs everything, including functions. on past few weeks, have been tarting our c++ code conform possible iso c++11 standard, using final draft document (n3242) guide.
as know, there occasional multiple declarations creep our code through externs appearing in more 1 file, or typedefs repeated. according excerpt section 7.1.3, page 145 of above doco, should harmless:
3. in given non-class scope, typedef specifier can used redefine name of type declared in scope refer type refers.
[ example:
typedef struct s { /* ... */ } s; typedef int i; typedef int i; typedef i;
— end illustration ]
so, wrote programme test this. in simplest form:
typedef int (fcntype)(int, int); extern fcntype fcn1; int fcn1(int x, int y) { homecoming x + y; } int main(int argc, char ** argv) { homecoming fcn1(2, 3); }
compiling using gcc
-wfatal-errors -wswitch-default -wswitch-enum -wunused-parameter -wfloat-equal -wundef -c -wstrict-null-sentinel -std=c++0x -pedantic -wall -wextra
there are, of course, no problems. let's dup function decl:
typedef int (fcntype)(int, int); extern fcntype fcn1; extern fcntype fcn1; // woops. #include ... int fcn1(int x, int y) { homecoming x + y; } int main(int argc, char ** argv) { homecoming fcn1(2, 3); }
as standard predicts, no problems. let's create different alter original:
typedef int (fcntype)(int, int=0); // default param. extern fcntype fcn1; int fcn1(int x, int y) { homecoming x + y; } int main(int argc, char ** argv) { homecoming fcn1(2); } // utilize default param
again, no problems. problem comes when have both duplicate decl , defaulted parameter this:
typedef int (fcntype)(int, int=0); // default param. extern fcntype fcn1; extern fcntype fcn1; // fyi line 3 in error message below. int fcn1(int x, int y) { homecoming x + y; } int main(int argc, char ** argv) { homecoming fcn1(2); } // utilize default param
and gcc complains
decltest.cpp:3: error: default argument given parameter 2 of ‘int fcn1(int, int)’
of course, cleaning code way should cleaned up, corralling decls one, improve organized file. bug in compiler or misunderstanding of mine default parameter "is"?
firstly, same function declaration same types, there should @ 1 declaration define default arguments. due §8.3.6 [dcl.fct.default]/4:
... default argument shall not redefined later declaration (not same value). [ example:
... void m() { void f(int, int); // has no defaults f(4); // error: wrong number of arguments void f(int, int = 5); // ok f(4); // ok, calls f(4, 5); void f(int, int = 5); // error: cannot redefine, same value } ...
— end example ] ...
also, @sven noticed, default argument shall not appear in typedef
, although g++ cannot grab -pedantic
. think clang , visual c++ reject haven't tried.
c++ c++11
Comments
Post a Comment