gpt4 book ai didi

c++ - 如果字符串有空格,则引发编译时错误

转载 作者:行者123 更新时间:2023-12-04 12:19:16 25 4
gpt4 key购买 nike

我有一个基类,打算由我正在编写的代码的其他用户继承,其中一个抽象函数返回对象的名称。由于项目的性质,名称不能包含空格。

class MyBaseClass {

public:

// Return a name for this object. This should not include whitespace.
virtual const char* Name() = 0;

};
有没有办法在编译时检查 Name() 的结果函数包含空格?我知道使用 constexpr 可以进行编译时操作函数,但我不确定以正确的方式向代码用户发出信号,告知他们的函数返回一个顽皮的字符串。
我也不清楚如何获得 constexpr编译器实际执行的函数来执行这样的检查(如果 constexpr 甚至是这样做的方法)。

最佳答案

我认为这在 C++20 中是可能的。
这是我的尝试:

#include <string_view>
#include <algorithm>
#include <stdexcept>

constexpr bool is_whitespace(char c) {
// Include your whitespaces here. The example contains the characters
// documented by https://en.cppreference.com/w/cpp/string/wide/iswspace
constexpr char matches[] = { ' ', '\n', '\r', '\f', '\v', '\t' };
return std::any_of(std::begin(matches), std::end(matches), [c](char c0) { return c == c0; });
}

struct no_ws {
consteval no_ws(const char* str) : data(str) {
std::string_view sv(str);
if (std::any_of(sv.begin(), sv.end(), is_whitespace)) {
throw std::logic_error("string cannot contain whitespace");
}
}
const char* data;
};

class MyBaseClass {
public:
// Return a name for this object. This should not include whitespace.
constexpr const char* Name() { return internal_name().data; }
private:
constexpr virtual no_ws internal_name() = 0;
};

class Dog : public MyBaseClass {
constexpr no_ws internal_name() override {
return "Dog";
}
};

class Cat : public MyBaseClass {
constexpr no_ws internal_name() override {
return "Cat";
}
};

class BadCat : public MyBaseClass {
constexpr no_ws internal_name() override {
return "Bad cat";
}
};
这里有几个想法在起作用:
  • 让我们使用类型系统作为文档和约束。因此,让我们创建一个类(上例中的 no_ws)来表示没有空格的字符串。
  • 对于在编译时强制执行约束的类型,它必须在编译时评估其构造函数。所以让我们创建构造函数 consteval .
  • 为保证派生类不违约,修改虚方法返回no_ws .
  • 如果要保留接口(interface)(即返回 const char* ),请将虚拟方法设为私有(private),并在公共(public)非虚拟方法中调用它。技术解释here .

  • 现在当然在这里我只检查有限的空白字符集并且与语言环境无关。我认为在编译时处理语言环境会非常棘手,所以也许更好的方法(工程方面)是明确指定名称中允许的一组 ASCII 字符(白名单而不是黑名单)。
    上面的例子不能编译,因为 "Bad cat"包含空格。注释掉 Bad cat类将允许代码编译。
    Live demo on Compiler Explorer

    关于c++ - 如果字符串有空格,则引发编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67925722/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com