gpt4 book ai didi

c++ - 函数体内的 typedef 是一种不好的编程习惯吗?

转载 作者:IT老高 更新时间:2023-10-28 12:43:05 26 4
gpt4 key购买 nike

我有一些类 C 并希望将其实例和方法的地址传递给测试函数 Test_C_Foo1() 中的某个仿函数。 Functor 是一个模板类,我必须提供类方法的类型 (MEMFN1) 作为其模板参数之一。我必须在某处定义 MEMFN1 类型,但不想更改 C.h 并且不想用它污染全局命名空间。我决定尽可能将 typedef 本地化,所以把它放在一个测试函数中——在 MEMFN1 实际使用的范围内。 在函数体内使用 typedef 是一种好习惯吗?

标准允许在函数体内使用 typedef,仅在以下特定情况下限制它:

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&);
};

ma​​in.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;
}

最佳答案

很好。它是合法的和本地化的。

关于c++ - 函数体内的 typedef 是一种不好的编程习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com