首页 > 解决方案 > constexpr 如何推导出值?

问题描述

我正在浏览 cppreference.com 中提到的 LiteralTypes 程序。(https://en.cppreference.com/w/cpp/named_req/LiteralType

我知道 constexpr 在编译期间推导出值。但在下面的情况下,第 10、12 和 16 行并不直接知道输入参数。(至少我看不出来)

那么它是如何推导出值的呢?

  1 #include <iostream>
  2 #include <stdexcept>
  3 
  4 class conststr
  5 {
  6     const char* p;
  7     std::size_t sz;
  8 public:
  9     template<std::size_t N>
 10     constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {}
 11 
 12     constexpr char operator[](std::size_t n) const
 13     {
 14         return n < sz ? p[n] : throw std::out_of_range("");
 15     }
 16     constexpr std::size_t size() const { return sz; }
 17 };
 18 
 19 constexpr std::size_t countlower(conststr s, std::size_t n = 0,
 20                                              std::size_t c = 0)
 21 {
 22     return n == s.size() ? c :
 23            s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) :
 24                                         countlower(s, n + 1, c);
 25 }
 26 
 27 // output function that requires a compile-time constant, for testing
 28 template<int n>
 29 struct constN
 30 {
 31     constN() { std::cout << n << '\n'; }
 32 };
 33 
 34 int main()
 35 {
 36     std::cout << "the number of lowercase letters in \"Hello, world!\" is ";
 37     constN<countlower("Hello, world!")>(); // implicitly converted to conststr
 38 }

标签: c++c++11constexpr

解决方案


当到达第 37 行时constN<countlower("Hello, world!")>();,编译器会尝试推断该值并将其替换到位。

所以编译器调用函数countlower("Hello, world!")。然后将参数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);Where 参数组成,nc在每次迭代时递增。

n是用于标记当前测试的字符位置的索引。 c表示小写字母的个数。

n到达结束索引时,所有递归调用都返回值并达到最终值。该值作为第 28 行定义的模板参数传递,并构造template<int n>新对象。constN

这一切都是在编译时完成的。

第二眼

将编译器想象成另一个C++程序,它定义了一个递归函数,该函数计算传递的字符串中低位字符的数量,并返回一个以该数字作为其成员的对象。

所以这:

constN<countlower("Hello, world!")>();

然后替换为:

constN<9>();

构造函数

好的。因此,让我们将结构想象constN成一个普通的结构或类,如下所示:

struct constN
{
    int n;

    // constructor for the object taking one argument
    constN(int n) : n(n) {};
}

在像我们这样随便的调用之后,constN(9)我们得到了一个对象n = 9。现在模板参数就是这样,但是您将它们传递到尖括号<>中。

所以这些是相等的:

struct CasualObject
{
    int n;

    CasualObject(int n) : n(n) {};
}

template<int n>
struct YourObject
{
    YourObject() { std::cout << n << '\n'; }
};

CasualconstN(9) == YourconstN<9>()

现在假设该countlower函数只是一个返回一些整数的普通函数。因此,您可以在创建将函数结果传递给构造函数的对象之前调用该函数。

所以这些是相等的:

int a = countlower("Hey");
constN obj1(a);

constN obj2(countlower("Hey"));

obj1 == obj2;

最后,编译器使用n = countlower("Hello, world!"). 现在让我们注意constN在第 31 行定义的唯一方法:

constN() { std::cout << n << '\n'; }

哇。它是一个构造函数。它与对象的类型具有相同的名称。因此,我们不仅基本调用构造函数,n = 9而且还执行它的主体。这意味着n打印到控制台。

最后,该对象constN未分配给任何变量。这意味着它永远不能被再次引用。智能编译器可能会一起删除第 37 行并用简单的打印语句替换它:

cout << 9 << '\n; // "Hello, world!" 中有 9 个小写字母`

隐式转换

所以问题是这样的:编译器如何知道N构造时应该是什么conststr

为了说明,我做了一个小程序:

#include <iostream>

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 std::size_t size() const { return sz; }
};

int main()
{
    char a[4] = "Hey";
    const char b[4] = "Hey";
    
    conststr x(a);
    conststr y(b);
    conststr z("Hey");
    
    printf("%lu %lu %lu", x.size(), y.size(), z.size());
    return 0;
}

现在,如果你运行它,你会得到 output 3 3 3。但是我在这里你哭了:“代码中只有 4s,最后一个对象完全没有声明大小。” 让我们一点一点地破译它:

char array首先,我们创建一些带有类型和const char array(本质上是指针)的字符串。

char a[4] = "Hey";
const char b[4] = "Hey";

它们包含 3 个字母和一个空终止符\0,这使它成为 4 个字符。当我们创建第一个conststr对象时:

conststr x(a);

a所以我们传递类型为 的变量char []char []可以转换为const char[]. const与修饰符基本相同。它也可以转换为std::string和许多其他。所以编译器认为它非常相似。到目前为止,我们已经定义了构造函数的这段代码:

conststr(const char(&a))
// which can be converted to all of these:
conststr(const char a[])
conststr(char* a)
conststr(char (&a))

但是定义了一个模板:

template<std::size_t N>
conststr(const char(&a)[N])

为了确定N应该是什么,编译器尝试重写参数的定义a以适应函数的需要。这称为隐式转换,并有一些规则:

  • 如果传递的参数匹配类型,就可以了
  • 如果没有,请尝试转换
  • 如果有转换,应用它
  • 如果在编译时不知道从传递类型到参数类型的转换,则引发编译错误
// so from main() we have:
char a[4] = "Hey";
// this can be rewritten like so:
const char a[4] = "Hey";
    
// now it looks very similar to the definition of the constructor:
const char(&a)[N]
const char a[4]

正如我之前所展示的,这些是相等的。所以现在,编译器可以将括号中的内容替换为N.

好的。但这不是 3... 如果我们查看构造函数的“主体”内部,我们会看到size sz分配了 value N - 1。这就是我们的 3。

conststr(const char(&a)[N]) : p(a),  sz(N - 1)
conststr(const char a[4]): p("Hey"), sz(4 - 1)

现在模板template<std::size_t N>只是告诉编译器该值应该在编译时计算或转换。所以你不能真正组成你自己的N,它总是取决于传入的字符串的长度。

好的,但是这个呢:

conststr z("Hey");

同样,编译器尝试将参数转换为合适的类型。并且因为它需要const char a[],所以它将被转换为那个。我已经介绍过了。


推荐阅读