在这个站点上,他们给出了一个文字类的例子:
#include <iostream>
#include <stdexcept>
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
}程序的输出结果
the number of lowercase letters in "Hello, world!" is 9但我不懂这个节目的任何一个部分。即这里的这一行:
constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {}const char(&a)[N],这个语法到底是什么意思?有名字吗?
发布于 2016-06-13 07:22:45
代码const char(&a)[N]需要括号来表示"a是一个引用:指向N const char的数组“。
如果没有括号,您将得到const char &a[N] --它将是"a是N const char引用的数组“,这是不允许的。
这就是为什么我更喜欢typedef,以使这类事情变得更清楚:
typedef const char ArrayN[N];
ArrayN &a = ...; // Whatever you want 'a' to refer tohttps://stackoverflow.com/questions/37783770
复制相似问题