使用另一种方法和#define定义常量使用函数

时间:2012-11-17 22:55:25

标签: c++ visual-studio-2010 c-preprocessor

有没有办法用另一种方法#define来定义常量使用函数?

例如,我在文件foo.cpp中有一个返回int:

的方法
int foo() { return 2; }

在我的bar.cpp中,我想要像

这样的东西
#define aConstant foo()

有可能吗?有办法吗?

(我正在使用Visual Studio 2010)

编辑:constexpr因为我使用的是VS 2010而无效,所以还有其他想法吗?

3 个答案:

答案 0 :(得分:2)

成功

constexpr int foo() { return 2; }

然后在另一个单位

static constexpr int aConstant = foo();

答案 1 :(得分:1)

在命名空间范围内的代码中的static int const a = bar();任何地方都没有任何内在错误。除非barconstexpr,否则初始化将在动态初始化阶段期间发生。这可能会导致某些排序问题,但它本身并没有被破坏,随后使用a将会像您想象的那样高效。

或者你可以把这个函数变成一个宏:

#define TIMESTWO(n) (n * 2)

答案 2 :(得分:1)

不幸的是,Visual C ++ 2010不支持C ++ 11带来的功能constexpr,因为您可以在this table(来自Apache Stdcxx项目)上看到它:MSVC(MicroSoft Visual studio C / C ++编译器) )还不支持(查看第7行)。

但是,您仍然可以将foo()正文保留在foo.cpp文件中并使用中间全局变量:

inline int foo() { return 2; }
const int aConstant = foo();

然后在bar.cpp档案中:

extern const int aConstant;

void bar()
{
   int a = 5 * aConstant;
}

如果您已将Visual C ++配置为允许内联(这是默认设置),则在编译时将初始化aConstant。否则,将在运行时调用foo()来初始化aConstant,但是在启动时(在调用main()函数之前)。所以这比每次使用foo()返回值时调用const要好得多。