簡體   English   中英

C++ 模板 - 完整指南:了解有關 decltype 和返回類型的腳注注釋

[英]C++ Templates - The Complete Guide: Understanding footnote comment about decltype and return type

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()是否有效。

這一切都是有道理的,我認為......

令我震驚的是腳注中的評論:

) does not require a nonreference, non- void return type to be complete, unlike call expressions in other contexts.除了decltype( )不需要非引用、非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; 測試以下內容

...相反確實添加了調用的返回類型是完整的要求...

但是void返回類型與不完整的返回類型不同。 為此你可以試試

struct X;

struct A {
    X begin() const;
};

在這里, X確實是不完整的,現在, 0很重要。 有了它,第一個static_assert不會通過,但它會在沒有, 0的情況下通過。

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM