如何在C++11中定义一个简单的常量值,使得没有运行时惩罚?例如:(无效代码)
// Not ideal, no type, easy to put in wrong spot and get weird errors
#define VALUE 123
// Ok, but integers only, and is it int, long, uint64_t or what?
enum {
Value = 123
};
// Could be perfect, but does the variable take up memory at runtime?
constexpr unsigned int Value = 123;
class MyClass {
// What about a constant that is only used within a class, so
// as not to pollute the parent namespace? Does this take up
// memory every time the class is instantiated? Does 'static'
// change anything?
constexpr unsigned int Value = 123;
// What about a non-integer constant?
constexpr const char* purpose = "example";
std::string x;
std::string metadata() { return this->x + (";purpose=" purpose); }
// Here, the compiled code should only have one string
// ";purpose=example" in it, and "example" on its own should not
// be needed.
};
编辑
因为有人告诉我这是一个无用的问题,因为没有背景知识,所以在此提供背景信息。
我正在定义一些标记,以便我可以做类似于这样的事情:
if (value & Opaque) { /* do something */ }
Opaque
的值在运行时不会改变,因此它仅在编译时需要使用,让它出现在编译后的代码中似乎很愚蠢。这些值还在循环内部使用,而该循环对图像中的每个像素运行多次,因此我想避免运行时查找,以避免减慢速度(例如,运行时进行内存访问以检索常量的值)。这不是过早优化,因为该算法目前需要约一秒钟来处理一个图像,而我经常需要处理100多个图像,因此我希望速度尽可能快。
由于有人说这很琐碎,不必担心,我猜#define
可能是最接近字面值的选项,因此也许这是避免“过度思考”问题的最佳选择?我想普遍共识是您只能希望没有人需要使用单词Opaque
或其他要使用的常量?
const int a = 0;
пјҢжңүж—¶еңЁзұ»дёӯдҪҝз”Ёstatic const int a = 0
гҖӮеҰӮжһңдёҚйңҖиҰҒеӯҳеңЁдәҺеҶ…еӯҳдёӯпјҢиҝҷдәӣеҸҳйҮҸеңЁиҝҗиЎҢж—¶дёҚдјҡеҚ з”ЁеҶ…еӯҳгҖӮ - Neil Kirk