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?

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>;

本文标签: cCan a deduced type be used as a type of a nontype template argumentStack Overflow