c++ - Is function overloading in a namespace (compared to a class with static members) a bad idea? -


this question idea rather real code

in past wrote many method overloadings , fine:

class myclass { public:      std::string method(type1 a)     {         return method(...);     }      std::string method(type2 a)     {         return ....;     }  } 

that working fantastic.

the problem began yesterday when wrote function overloading namespace:

namespac myspace {      std::string func(type1 a)     {         return func(...);     }      std::string func(type2 a)     {         return ....;     }  } 

here, problem inside namespace, compiler not know second function. so, tries convert given type matches first function. unfortunately compiler did not tell me mistake me. although sent type2 function, tried convert type1 call , result stackoverflow.

even though changing order of functions fix problem, wonder using function overloading in namespace bad idea in professional c++ programming?

as commented, problem not overloading function, rather, order of function declaration.

the error in namespace clear, when compiler see

std::string func(type1 a) {     return func(/*expect type2*/); } 

it must know prototype/definition of func(/*expect type2*/) @ time.

however, in class definition:

class myclass { public:      std::string method(type1 a)     {         return method(/*expect type2*/); // okay, no problem here     }      std::string method(type2 a)     {         return ....;     } } 

compiler not throw error although prototype/definition of method(/*expect type2*/) not known @ location. why?

according http://www.tutorialspoint.com/cplusplus/cpp_inline_functions.htm

a function definition in class definition inline function definition, without use of inline specifier.

that means, when compiler compiles myclass, compiles member prototype only, of course, in example, no error. member definition compiled later e.g. when invoke member. @ time, prototype of member functions in myclass known. thus, compiler won't throw error.

edit: namespace namespace, class class; have different meaning. choosing either namespace or class depends on own situation rather desire rid of function order error. in example, can still use namespace declaring needed prototypes:

namespac myspace {     std::string func(type2 a); // prototype      std::string func(type1 a)     {         return func(...); // fine     } } 

so, best practice declaring prototype before definition/calling :)


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -