简体   繁体   English

C++20 概念匹配字符串文字

[英]C++20 concept matching string literal

In C++20 it is possible to write a wrapper class which only accepts string literals.在 C++20 中,可以编写一个只接受字符串文字的包装器 class。

struct string_literal
{
    template<size_t N>
    consteval Wrapper(char const (&s)[N]) : p(s) {}

    char const* p;
};
void takes_literal(string_literal lit) {
  // use lit.p here
}

from OP's own answer here https://stackoverflow.com/a/74922953来自 OP 自己的回答https://stackoverflow.com/a/74922953


Is it also possible to write a concept that only matches string literals?是不是也可以写一个只匹配字符串字面量的概念?

A char const* which points into a string literal is virtually no different from any other char const* .指向字符串文字的char const*实际上与任何其他char const*没有什么不同。 The fact that a literal starts its life as an array is irrelevant, as non-literal character arrays can also be created.文字以数组开始其生命这一事实是无关紧要的,因为也可以创建非文字字符 arrays。 To my knowledge, there is exactly one difference: pointers to string literals cannot be used as non-type template parameters.据我所知,只有一个区别:指向字符串文字的指针不能用作非类型模板参数。

That's not particularly helpful.这不是特别有用。 Even if we were restricted to compile-time code execution, you can get non-literal char const* s which also cannot be used as NTTPs (by creating a std::string , which can now be done at compile-time. You can call constexpr functions on string::c_str s pointer, but you can't use the result as an NTTP).即使我们被限制在编译时代码执行,你也可以获得非文字char const* s,它也不能用作 NTTP(通过创建std::string ,现在可以在编译时完成。你可以在string::c_str指针上调用constexpr函数,但不能将结果用作 NTTP)。

The best you can do is to create a user-defined literal operator that returns your string_literal object. You can make it so that only this literal operator can construct such a type (besides copying, of course).你能做的最好的事情就是创建一个用户定义的文字运算符,它返回你的string_literal你可以做到只有这个文字运算符才能构造这样的类型(当然除了复制)。 But even then, they can call your operator"" directly with a non-literal, and there is nothing you can do about it.但即使那样,他们也可以直接用非文字调用你的operator"" ,而你对此无能为力

Instead, you should re-evaluate why you need to know if it is a string literal specifically .相反,你应该重新评估为什么你需要知道它是否是一个特定的字符串文字。

Whereas const char(&)[N] isn't necessary a string literal, you might create concept to match const char(&)[N] :const char(&)[N]不一定是字符串文字,您可以创建概念来匹配const char(&)[N]

template <typename T>
struct is_str_literal_impl : std::false_type{};

template <std::size_t N>
struct is_str_literal_impl<const char[N]> : std::true_type{};

template <typename T>
concept concept_str_literal = is_str_literal_impl<T>::value;

void takes_literal(concept_str_literal auto&  lit) {
  // use lit.p here
}

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM