6

这个 Cpp 示例代码什么意思,没看懂

 2 years ago
source link: https://www.v2ex.com/t/861587
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Linux

这个 Cpp 示例代码什么意思,没看懂

  James369 · 1 小时 26 分钟前 · 379 次点击

这段代码是用来计数小写字母的,但有个地方不理解

//Literal type that extends string literals:

class conststr
{
    const char* p;
    std::size_t sz;
public:
    template<std::size_t N>
    constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {}
 
    constexpr char operator[](std::size_t n) const
    {
        return n < sz ? p[n] : throw std::out_of_range("");
    }
 
    constexpr std::size_t size() const { return sz; }
};
 
constexpr std::size_t countlower(conststr s, std::size_t n = 0,
                                             std::size_t c = 0)
{
    return n == s.size() ? c :
        s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) :
                                     countlower(s, n + 1, c);
}
 
// output function that requires a compile-time constant, for testing
template<int n>
struct constN
{
    constN() { std::cout << n << '\n'; }
};
 
int main()
{
    std::cout << "the number of lowercase letters in \"Hello, world!\" is ";
    constN<countlower("Hello, world!")>(); // implicitly converted to conststr
}

不理解之处:构造的时候 constexpr conststr(const char(&a)[N]),这个 N 是怎么传进来的?

原文在此: https://en.cppreference.com/w/cpp/named_req/LiteralType, 怎么搞这么复杂的 template ,阅读起来有点障碍.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK