了解C++ 98中的Enable_if实现

发布于 2025-02-07 03:39:27 字数 334 浏览 2 评论 0原文

我已经将其视为enable_if for c ++ 98的自称实现:

template<bool b, typename T = void>
struct enable_if {
    typedef T type;
};

template<typename T>
struct enable_if<false, T> {};

但是,我个人不明白。我看不到布尔人在哪里开始玩游戏。如果有人会为我解开它,真的很感激。

I have seen this given as a self-explanatory implementation of enable_if for C++98 :

template<bool b, typename T = void>
struct enable_if {
    typedef T type;
};

template<typename T>
struct enable_if<false, T> {};

But alas I personally don't understand it. I don't see where the boolean kicks into play. Would really appreciate if someone would unwrap it for me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤寂小茶 2025-02-14 03:39:27

首先考虑这一点:

template<bool b>
struct foo {
    static const bool B = b;
};

template <>
struct foo<false> {
    static const bool B = false;
};

它是主要模板和专业化。在一般情况下,foo&lt; b&gt; :: b只是b。在特殊情况下,当b == false专业启动时,foo&lt; :: b is false

您的std :: enable_if的示例有两个不同的原因:a)它正在使用部分专业化。专业化是针对任何类型的tb == false;。 b)在专业中,没有类型成员别名。这就是std :: enable_if的全部目的。当条件为false时,std :: enable_if&lt;条件,t&gt; ::类型是一个替代故障,因为专业化没有type。当条件true然后std :: enable_if; condition t&gt; :: type只是t

First consider this:

template<bool b>
struct foo {
    static const bool B = b;
};

template <>
struct foo<false> {
    static const bool B = false;
};

Its a primary template and a specialization. In the general case foo<b>::B is just b. In the special case when b == false the specialization kicks in and foo<false>::B is false.

Your example of std::enable_if is different for two reasons: A) It is using partial specialization. The specialization is for any type T and b == false;. B) in the specialization there is no type member alias. And thats the whole purpose of std::enable_if. When the condition is false then std::enable_if< condition, T>::type is a substitution failure, because the specialization has no type. When the condition is true then std::enable_if<condition,T>::type is just T.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文