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;
}
It's good. It's legal and localized.