我正在尝试编写一个函数“my_func()”,该函数在编译时计算字符串中字符“a”的数量,这使得当“a”的计数错误时代码无法编译。
我受到了 C++ 标准库中函数
std::format()
的启发,该函数检查编译器中{}
的数量。
我使用的编译器是msvc,C++20。
我下面的代码无法编译,因为我不知道如何实现这样的功能。那么我该如何修复功能
my_func()
?
template <size_t Size>
auto my_func(const char(&str)[Size]) -> void {
// dosomething...
constexpr size_t count = 0;
const char* c = str;
for (size_t i = 0; i < Size; ++i) {
if (*c == 'a') {
count++; // const values cannot be modified
}
c++;
}
// If the variable `count ` is not set to constexpr, an error will be reported here.
static_assert(count == 2);
// dosomething...
}
auto main() -> int {
my_func("abc abc"); // is error
}
关键是
std::format
检查 consteval
的 std::format_string
构造函数,确保格式字符串参数格式正确并且适合后面的 std::format
参数。
这意味着你需要反转你的逻辑;最简单的方法是编写一个
counting_string
类型,其 consteval
构造函数仅接受包含 2 个 'a'
的字符串文字:
struct counting_string {
template<unsigned Size>
consteval explicit(false) counting_string(char const (&str)[Size]) {
unsigned count = 0;
const char* c = str;
for (unsigned i = 0; i < Size; ++i) {
if (*c == 'a') {
count++; // const values cannot be modified
}
c++;
}
if (count != 2) throw "invalid str";
}
};
auto my_func(counting_string str) -> void {
; // if we get here we know `str` contains 2 'a's
}
示例.
对于样式点,您可能需要制作
counting_string
类模板。