c++ - Can a deduced type be used as a type of a non-type template argument? - Stack Overflow

In the blog post Passing String Literals as Template Parameters in C++20, I saw this code snippet:temp

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?

Share Improve this question edited Mar 25 at 15:54 Remy Lebeau 601k36 gold badges507 silver badges851 bronze badges asked Mar 25 at 15:04 PetrPetr 63.5k13 gold badges161 silver badges329 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

It 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 variable x in the invented declaration T 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信