gpt4 book ai didi

c++ - 将字符串文字传递给模板字符数组参数

转载 作者:行者123 更新时间:2023-12-03 21:40:38 25 4
gpt4 key购买 nike

CTRE library能够在编译时使用类似 ctre::match<"REGEX">(text_to_search) 的语法解析和验证正则表达式.我知道这种语法仅在 C++20 中受支持,这很好,但是无论我尝试什么,我都无法以这种方式使用字符串文字。这是一个非常简单的例子:

// The compiler refuses to pass string literals to STR in this compile time version.
template <char const STR[2]> constexpr int to_int_compile_time()
{
return STR[0] - '0';
}

// It has no problems passing the string literal to str in this version.
int to_int_runtime(char const str[2])
{
return str[0] - '0';
}
调用 to_int_runtime("0")工作正常,但 to_int_compile_time<"0">()提示字符串文字不能用于此模板参数。应该怎么做 to_int_compile_time写成字符串文字可以传递到字符数组模板参数?

最佳答案

能够做到这一点取决于 C++20 的一个鲜为人知的特性:非类型模板参数可以具有类模板类型,没有指定模板参数 . CTAD 将确定这些论点。
所以你创建了一个由 size_t N 模板化的类,即有 char[N]作为成员,可以从一个构建,并且 N可以通过 CTAD 推导出来。
例子:

// This does nothing, but causes an error when called from a `consteval` function.
inline void expectedNullTerminatedArray() {}

template <std::size_t N>
struct ConstString
{
char str[N]{};

static constexpr std::size_t size = N - 1;

[[nodiscard]] std::string_view view() const
{
return {str, str + size};
}

consteval ConstString() {}
consteval ConstString(const char (&new_str)[N])
{
if (new_str[N-1] != '\0')
expectedNullTerminatedArray();
std::copy_n(new_str, size, str);
}
};
那你做 template <ConstString S> struct A {...}; ,并使用 S.strS.view()检查字符串。
以下是此类的一些额外便利运算符:
template <std::size_t A, std::size_t B>
[[nodiscard]] constexpr ConstString<A + B - 1> operator+(const ConstString<A> &a, const ConstString<B> &b)
{
ConstString<A + B - 1> ret;
std::copy_n(a.str, a.size, ret.str);
std::copy_n(b.str, b.size, ret.str + a.size);
return ret;
}

template <std::size_t A, std::size_t B>
[[nodiscard]] constexpr ConstString<A + B - 1> operator+(const ConstString<A> &a, const char (&b)[B])
{
return a + ConstString<B>(b);
}

template <std::size_t A, std::size_t B>
[[nodiscard]] constexpr ConstString<A + B - 1> operator+(const char (&a)[A], const ConstString<B> &b)
{
return ConstString<A>(a) + b;
}
您还可以使用此类的模板 UDL:
template <ConstString S>
struct ConstStringParam {};

template <ConstString S>
[[nodiscard]] constexpr ConstStringParam<S> operator""_c()
{
return {};
}

// -----

template <ConstString S> void foo(ConstStringParam<S>) {}

foo("Sup!"_c);

关于c++ - 将字符串文字传递给模板字符数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68024563/

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