如何在C++编译时检测const char*格式错误?

问题描述 投票:0回答:1

我正在尝试编写一个函数“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
}
c++ templates constexpr compile-time
1个回答
0
投票

关键是

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
类模板

© www.soinside.com 2019 - 2024. All rights reserved.