代码中奇怪的constexpr参数

时间:2013-06-08 22:34:44

标签: c++ c++11

我正在尝试理解代码:

#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构造函数有什么意义?

2 个答案:

答案 0 :(得分:4)

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

关键是它允许编译器推导出数组的长度。如果没有引用,const char a[N]作为参数将等同于const char* a,它不允许推导出模板参数N

答案 1 :(得分:2)

这是(以及template<std::size_t N>部分),一种获取常量字符串大小的方法,所以你可以这样做:

conststr hello("Hello, World!"); 

以后:

size_t s = hello.size();