![](/img/trans.png)
[英]Is it bad programming practice to have a function that prints statement?
[英]Is typedef inside of a function body a bad programming practice?
我有一些 class C
并想将其实例和方法的地址传递给测试 function Test_C_Foo1()
中的某个仿函数。 Functor 是一个模板 class,我必须提供 class 方法 ( MEMFN1
) 的类型作为其模板参数之一。 我必须在某处定义MEMFN1
类型,但不想更改C.h
并且不想用它污染全局命名空间。 我决定尽可能地本地化typedef ,所以将它放在测试函数中 - 在实际使用 MEMFN1 的MEMFN1
中。 在 function 体内使用 typedef 是一个好习惯吗?
标准允许在 function 主体内使用typedef ,仅在这些特殊情况下对其进行限制:
typedef 说明符不得在 decl-specifier-seq 中与类型说明符以外的任何其他类型的说明符组合,并且不得在参数声明 (8.3.5) 的 decl-specifier-seq 中使用,也不在函数定义 (8.4) 的 decl-specifier-seq 中。
这是代码片段:
C.h:
...
#include <string>
...
class C
{
public:
int foo1(const std::string&);
};
主.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;
}
这很好。 它是合法的和本地化的。
恕我直言,如果typedef
只是为了避免键入或使指向成员函数的指针不那么麻烦,如您的示例所示,那很好。
但是如果typedef
揭示了一些特定的概念,那么它应该在 function 之外可见。
检查它的快速测试是typedef
的名称:
typedef int(C::*MEMFN1)(const std::string&); //OK: as local typedef, just an abbreviation
typedef int(C::*ACTION)(const std::string&); //Not so OK: Action is a new concept
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.