代码中奇怪的constexpr参数 [英] Weird constexpr argument in code

查看:42
本文介绍了代码中奇怪的constexpr参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解代码:

#include <iostream>
#include <stdexcept>

// constexpr functions use recursion rather than iteration
constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}

// literal class
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 functions signal errors by throwing exceptions from operator ?:
    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 << "4! = " ;
    constN<factorial(4)> out1; // computed at compile time

    volatile int k = 8; // disallow optimization using volatile
    std::cout << k << "! = " << factorial(k) << '\n'; // computed at run time

    std::cout << "Number of lowercase letters in \"Hello, world!\" is ";
    constN<countlower("Hello, world!")> out2; // implicitly converted to conststr
}

参数是什么

const char(&a)[N]

?我不明白..似乎是对数组的引用..将它传递给constexpr构造函数有什么意义?

? I don't understand it.. seems like a reference to an array.. and what's the point in passing it to a constexpr constructor?

推荐答案

参数 const char(& a)[N] 是对数组的引用。

The parameter const char(&a)[N] is a reference to an array.

它的要点是它允许编译器推断数组的长度。如果没有引用,作为参数的 const char a [N] 等效于 const char * a 而不是允许推导模板参数 N

The point of it is that it allows the compiler to deduce the length of the array. Without the reference, const char a[N] as parameter would be equivalent to const char* a which doesn't allow the template parameter N to be deduced.

这篇关于代码中奇怪的constexpr参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆