這個 if 陳述句可以用#if ....宏代替嗎?
可能不必包含(太多)額外的標題。
#include <cstdint>
#include <string>
///Parse a string to obtain a fixed width type
inline uint64_t stou64(const std::string& in) {
if (sizeof(unsigned long) == sizeof(uint64_t)) {
return std::stoul(in);
} else {
return std::stoull(in);
}
}
uj5u.com熱心網友回復:
為此,您不需要前處理器宏。無論大小如何,該函式都定義良好,并且編譯器足夠聰明,可以完全優化未使用的分支。
如果您想確保即使禁用優化也洗掉未使用的分支,您可以使用if constexpr。只需constexpr在您的示例中添加 if 之后。
如果您不需要支持當前活動的語言環境,請考慮std::from_chars改用。
uj5u.com熱心網友回復:
我更喜歡這種方法(在 C 17 之前std::from_chars):
template<typename T>
T string_to(const std::string& in);
template<>
int string_to<int>(const std::string& in) {
return std::stoi(in);
}
template<>
unsigned string_to<unsigned>(const std::string& in) {
return std::stol(in);
}
template<>
long string_to<long>(const std::string& in) {
return std::stol(in);
}
template<>
long long string_to<long long>(const std::string& in) {
return std::stoll(in);
}
template<>
unsigned long string_to<unsigned long>(const std::string& in) {
return std::stoul(in);
}
template<>
unsigned long long string_to<unsigned long long>(const std::string& in) {
return std::stoull(in);
}
inline uint64_t stou64(const std::string& in) {
return string_to<uint64_t>(in);
}
https://godbolt.org/z/T57cbq91z
uj5u.com熱心網友回復:
不,您的if陳述句不同,因為 if 和 else 路徑都被編譯并且必須是有效的運算式,即使編譯器隨后將代碼優化為僅采用的路徑。在#if宏中,編譯器只能看到剩余的部分。對于給定的論點,消除的部分不必是有意義的。
由于這可能是模板的問題,因此在 c 17 中添加了constexpr if語法。
#include <cstdint>
#include <string>
///Parse a string to obtain a fixed width type
inline uint64_t stou64(const std::string& in) {
if constexpr (sizeof(unsigned long) == sizeof(uint64_t)) {
return std::stoul(in);
} else {
return std::stoull(in);
}
}
注意:在這個特定的例子中,這無關緊要。但為什么不習慣if constexpr呢?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474912.html
