Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typedef inside of a function body a bad programming practice?

Tags:

c++

typedef

I have some class C and want to pass address of its instance and method to some functor in a test function Test_C_Foo1(). Functor is a template class and I have to provide type of the class method (MEMFN1) as one of its template parameters. I have to define MEMFN1 type somewhere but don't want to change C.h and don't want to pollute global namespace with it. I decided to localize typedef as much as possible so put it inside a test-function - within the scope where MEMFN1 is actually used. Is using a typedef inside the function body a good practice?

Standard allows using typedef inside a function body, restricting it only in these particular cases:

The typedef specifier shall not be combined in a decl-specifier-seq with any other kind of specifier except a type-specifier, and it shall not be used in the decl-specifier-seq of a parameter-declaration (8.3.5) nor in the decl-specifier-seq of a function-definition (8.4).

Here's the code snippet:

C.h:

... #include <string> ...  class C { public:     int foo1(const std::string&);        }; 

main.cpp:

... #include "C.h" ...  void Test_C_Foo1() {    typedef int(C::*MEMFN1)(const std::string&);     C c;       Functor1<C, MEMFN1,...> f1(&c, &C1::foo1,...);    ... }  ...  int main() {     Test_C_Foo1();     return 0; } 
like image 724
Bojan Komazec Avatar asked Apr 11 '12 09:04

Bojan Komazec


People also ask

Is typedef good practice?

Best PracticesUse a typedef for each new type created in the code made from a template. Give the typedef a meaningful, succinct name. Sometimes, typedefs should also be created for simple types. Again, a uniquely identifiable, meaningful name for a type increases maintainablity and readability.

Is typedef deprecated C++?

In MSVC++, you can deprecate typedef like this: typedef __declspec(deprecated) int myint; The MSVC++ compiler will generate warning that myint is deprecated! @KitsuneYMG: Yes.

Can typedef be in Main?

typedef unsigned long int ulint; typedef float real; After these two declarations, ulint is an alias of unsigned long int and real is an alias of float . Here typedef definition is inside main() function so we can use alias uchar only inside the main() .

What happens internally when we create typedef?

Internally there will happen nothing because it is only the information for the compiler that you introduced some alias for another type. ... A typedef declaration does not introduce a new type, only a synonym for the type so specified.


1 Answers

It's good. It's legal and localized.

like image 119
justin Avatar answered Sep 21 '22 22:09

justin