- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在浏览cppreference.com中提到的LiteralTypes程序。
(https://en.cppreference.com/w/cpp/named_req/LiteralType)
我知道constexpr会在编译时推断出该值。
但是在下面的情况下,第10、12和16行不直接知道输入参数。 (至少我看不出来)
那么如何推算值(value)呢?
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 }
最佳答案
当到达第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);
组成,其中参数n
和c
在每次迭代时都会递增。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行,并用简单的print语句替换它:
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;
}
现在,如果运行该命令,将获得输出
3 3 3
。但是我在这里让您大哭:“代码中只有4,最后一个对象的大小完全没有声明。”让我们对它进行一点一点的解密:
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
放置。
size sz
被分配了值
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[]
,所以它将被转换为那个。我已经介绍过了。
关于c++ - constexpr如何推导值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61362393/
在 ubuntu gcc 8.0 中: void bar(){} constexpr int foo(int a) { if (a <=0 ) bar(); retur
考虑一个在运行时只包装一个值的类: template class NonConstValue { public: NonConstValue(const Type& val)
在试验 constexpr 函数和模板(以及非类型模板参数)时,我偶然发现了一个现象,我无法理解是哪条规则使它生效。 所以根据 constexpr-s 的规则,我的问题本质上是“为什么会发生这种情况”
我正在阅读 Nicolai M. Josuttis 所著的“C++ 17 The Complete Guide”一书,无法理解以下示例 auto squared1 = [](auto val) con
(使用 g++ 7.0 主干。) 给定以下“类型到值包装”实用程序... template struct type_wrapper { using type = T; }; // "Wraps" a
我编写了一些代码,它能够根据调用站点提供与给定函数关联的字符串(通过函数指针和并行数组的tuple)来分派(dispatch)给函数。 dispatch 函数不直接接受字符串,而是接受 Callabl
如果我想使用一些方便的东西,比如 make_array 我没有机会先声明我的数组,然后再像“早些时候”那样进行定义,因为我的 var 类型不可用定义前。 所以我找到了这个答案: Undefined r
使用 gcc (HEAD 7.0.0 201612) 我惊讶地发现这有效: constexpr long value(const char *definition) { if (definit
我有这个片段。 #include #include struct JustStr { JustStr(const std::string& x) : val(x) {} stati
我找不到任何关于新 C++17 if 初始化语法的信息和“constexpr if”在: http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p01
考虑以下函数: template auto concatenate(std::array &data1, std::array &data2) { std::array result;
假设我有以下对象: #include class Foo { public: constexpr Foo() {}; constexpr std::string foo() cons
我正在尝试使用 https://github.com/gdelugre/literal_ipaddr它说它是一个 C++17 constexpr implementation of inet_addr
我想重新定义unique_ptr用一个特殊的析构函数。因此,我使用以下代码尝试模仿 unique_ptr 的一些构造函数.遗憾constexpr施 worker 员拒绝 build ,我不知道为什么。
我想用结构名称的哈希值初始化一个结构成员。 constexpr uint32_t myHash(const char* const data) { //Some code for hash r
我正在尝试编译 C++ 库(使用 gcc 5.3.1-14ubuntu2)并遇到此类错误: > In file included from > /root/pitchfork/workspace/un
设置: 我有一个使用 SIMD 内部函数的函数,我想在一些 constexpr 函数中使用它。 为此,我需要将其设为 constexpr。但是,SIMD 内在函数没有标记为 constexpr,编译器
这是一个简化的代码示例,旨在生成任意值序列(在 std::iota 的意义上)和在它们之上的不同类别的迭代器: struct delta { template void inc(I&
考虑以下函数: template auto concatenate(std::array &data1, std::array &data2) { std::array result;
我偶然发现了调用非 constexpr 函数的 constexpr 模板函数:在以下代码段中,由于调用了非 constexpr set,bar 无法按预期编译,但 foo 可以编译。谁能告诉我 foo
我是一名优秀的程序员,十分优秀!