函数体内的typedef是不好的编程习惯吗? [英] Is typedef inside of a function body a bad programming practice?

查看:51
本文介绍了函数体内的typedef是不好的编程习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类 C ,并且希望将其实例和方法的地址传递给测试函数 Test_C_Foo1()中的某个函子.Functor是模板类,我必须提供类方法的类型( MEMFN1 )作为其模板参数之一.我必须在某个地方定义 MEMFN1 类型,但是不想更改 C.h ,也不想使用它来污染全局名称空间.我决定尽可能地对 typedef 进行本地化,因此将其放在测试函数中-在实际使用 MEMFN1 的范围内.在函数体内使用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允许在函数体内使用 typedef ,仅在以下特定情况下对其进行限制:

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

typedef说明符不得在decl-specifier-seq中组合除类型说明符外,还应与任何其他种类的说明符一起使用,并且不能在参数声明的decl-specifier-seq中使用(8.3.5)或函数定义(8.4)的decl-specifier-seq中也没有.

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).

这是代码段:

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.

这篇关于函数体内的typedef是不好的编程习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆