在这个网站上,他们给出了一个字面类的例子:
该程序的结果为输出。
但是我不理解这个程序的一部分。即,这里的这一行代码:
#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]
这个语法究竟是什么意思?它有一个专门的名称吗?
template <size_t N> using ArrayN = const char[N];
,从而提供constexpr conststr(ArrayN<N>& a)
。 - Calethtypedef
绝对没有错误。实际上,typedef
被使用得正是它的预期用途... - John BurgerN
是函数的模板参数时,typedef就没有存在的必要了。 - Calethtypedef
的例子仍然相关 - 只是不适用于这种情况!(不知道这种语言将来是否会允许呢?) - John Burger