admin管理员组文章数量:1400087
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>;
本文标签: cCan a deduced type be used as a type of a nontype template argumentStack Overflow
版权声明:本文标题:c++ - Can a deduced type be used as a type of a non-type template argument? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744187239a2594349.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论