【问题标题】:C++ - ampersand+brackets array syntax? [duplicate]C++ - 和号+括号数组语法? [复制]
【发布时间】:2016-10-13 12:27:15
【问题描述】:

在这个site 上,他们给出了一个文字类的例子:

#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(&amp;a)[N],这个语法到底是什么意思?有名字吗?

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    代码const char(&amp;a)[N] 需要用括号表示“a 是一个引用:Nconst chars 的数组”。

    如果没有括号,您将得到 const char &amp;a[N] - 这将是“aN const char 引用的数组”,这是不允许的。

    这就是为什么我更喜欢typedefs,让这些事情更清楚:

    typedef const char ArrayN[N];
    
    ArrayN &a = ...; // Whatever you want 'a' to refer to
    

    【讨论】:

    • 请注意,您不能在所示情况下使用 typedef。您可以使用别名模板,例如template &lt;size_t N&gt; using ArrayN = const char[N];,给出constexpr conststr(ArrayN&lt;N&gt;&amp; a)
    • @Caleth 我承认我的例子是不完整的 [现在放大] - 但 typedef 肯定不是不正确的。事实上,typedef完全按照它的原意使用......
    • N 是函数的模板参数时,typedef 没有位置
    • @Caleth 啊,你是对的。这是几年前的复活,我忘记了最初的前提。但是,typedef 示例仍然是相关的——只是在这种情况下不适用! (不知道将来语言会不会允许呢?)
    猜你喜欢
    • 2020-06-21
    • 2015-11-13
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多