有没有办法使用另一个方法的函数定义一个常量#define?
例如,我在文件 foo.cpp 中有一个返回 int 的方法:
int foo() { return 2; }
在我的 bar.cpp 中,我想要类似的东西
#define aConstant foo()
是否可以?有没有办法做到这一点?
(我正在使用 Visual Studio 2010)
编辑:constexpr因为我使用的是 VS 2010,所以不起作用,所以还有其他想法吗?
有没有办法使用另一个方法的函数定义一个常量#define?
例如,我在文件 foo.cpp 中有一个返回 int 的方法:
int foo() { return 2; }
在我的 bar.cpp 中,我想要类似的东西
#define aConstant foo()
是否可以?有没有办法做到这一点?
(我正在使用 Visual Studio 2010)
编辑:constexpr因为我使用的是 VS 2010,所以不起作用,所以还有其他想法吗?
做了
constexpr int foo() { return 2; }
然后在另一个单元
static constexpr int aConstant = foo();
static int const a = bar();在命名空间范围内的代码中的任何地方都没有任何本质上的错误。只是除非bar是constexpr,否则初始化将发生在动态初始化阶段。这可能会导致某些排序问题,但它本身并没有被破坏,后续使用a将与您想象的一样高效。
或者,您可以将函数设为宏:
#define TIMESTWO(n) (n * 2)
不幸的是,Visual C++ 2010 不支持constexprC++11 带来的功能,正如您在此表上看到的那样(来自 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返回值时调用要好得多。