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和返回类型的脚注注释


- 将 hdc 内容复制到位图 2022-09-04
- 将函数的返回值分配给引用 C++? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01