In the blog post Passing String Literals as Template Parameters in C++20, I saw this code snippet:
template<size_t N>
struct StringLiteral {
constexpr StringLiteral(const char (&str)[N]) {
std::copy_n(str, N, value);
}
char value[N];
};
template<StringLiteral lit>
void Print() { /* ... */ }
What allows using template<StringLiteral lit>
without the size_t N
parameter of StringLiteral
?
In the blog post Passing String Literals as Template Parameters in C++20, I saw this code snippet:
template<size_t N>
struct StringLiteral {
constexpr StringLiteral(const char (&str)[N]) {
std::copy_n(str, N, value);
}
char value[N];
};
template<StringLiteral lit>
void Print() { /* ... */ }
What allows using template<StringLiteral lit>
without the size_t N
parameter of StringLiteral
?
1 Answer
Reset to default 0It turns out it's possible if an appropriate deduction guide is provided:
From https://en.cppreference/w/cpp/language/template_parameters, section Non-type template arguments:
If
T
contains a placeholder type, or is a placeholder for a deduced class type, the type of the template parameter is the type deduced for the variablex
in the invented declarationT x = E;
.
Therefore we just need to supply:
template <size_t N>
StringLiteral(const char (&str)[N]) -> TemplateStringLiteral<N>;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744187240a4562264.html
评论列表(0条)