C++ Templates - The Complete Guide: Understanding footnote comment about decltype and return type(C++模板-完整指南:了解有关dectype和返回类型的脚注注释)
问题描述
C++模板-完整指南第2版在第435页提供了以下代码
#include <string>
#include <type_traits>
template<typename T, typename = void>
struct HasBeginT : std::false_type {};
template<typename T>
struct HasBeginT<T, std::void_t<decltype(std::declval<T>().begin())>>
: std::true_type {};
并评论decltype(std::declval<T>().begin())用于测试在T上调用.begin()是否有效。
我认为这一切都有道理…
让我吃惊的是脚注中的评论:
不同于其他上下文中的调用表达式,
decltype(call-expression)不要求非引用、非void返回类型是完整的。相反,使用decltype(std::declval<T>().begin(), 0)确实增加了调用的返回类型必须完整的要求,因为返回值不再是decltype操作数的结果。
我不太明白。
在尝试使用它时,我尝试使用以下代码查看它对void成员begin的行为。
struct A {
void begin() const;
};
struct B {
};
static_assert(HasBeginT<A>::value, "");
static_assert(!HasBeginT<B>::value, "");
但这两个断言都通过或不使用, 0。
推荐答案
您的演示使用void begin() const;测试以下内容
..。而是添加了调用的返回类型为Complete.
的要求
但void返回类型与不完整的返回类型不同。为此,您可以尝试
struct X;
struct A {
X begin() const;
};
这里,X确实是不完整的,现在, 0很重要。使用它,第一个static_assert不会通过,但它不会通过, 0。
demo
这篇关于C++模板-完整指南:了解有关dectype和返回类型的脚注注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++模板-完整指南:了解有关dectype和返回类型的脚注注释
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
