使用 enable_if 来防止声明? [英] Using enable_if to prevent declaration?

查看:49
本文介绍了使用 enable_if 来防止声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stroustrup C++ 4th Ed Page 796 指出如果 Enable_if 的条件计算结果为 false,则它所属的整个函数声明将被完全忽略.";和......我们不声明任何东西.".

Stroustrup C++ 4th Ed Page 796 states that "If Enable_if’s condition evaluates to false, the whole function declaration of which it is part is completely ignored." and "...we don’t declare anything.".

有人知道为什么要声明第一个 f0() 吗?我是否正确使用了 enable_if?

Does anyone know why the first f0() is being declared? Am I using enable_if correctly?

我的目标是禁用其中一项声明.我不确定 f0() 如何有返回类型,因为 false 版本应该缺少 ::type.

My goal is to disable one of the declarations. I'm not sure how both f0() can have a return type, as the false version should be missing ::type.

#include <type_traits>
using namespace std;

template<bool B, typename T>
using Enable_if = typename std::enable_if<B,T>::type;

template <class T>
class X {
    Enable_if<false, T> f0(int x) {};
    Enable_if<true, T> f0(int x) {};
};

int main(void)
{
    X<void> xx;
    return 0;
}

编译:

clang++ -std=c++11 -Wall -pedantic test197.cc && ./a.out
test197.cc:10:24: error: functions that differ only in their return type cannot
      be overloaded
    Enable_if<true, T> f0(int x) {};
    ~~~~~~~~~~~~~~~~~~ ^
test197.cc:9:25: note: previous definition is here
    Enable_if<false, T> f0(int x) {};
    ~~~~~~~~~~~~~~~~~~~ ^
1 error generated.

推荐答案

你不能使用这种方式,因为你的对象在任何情况下都会被创建,因为该类没有创建或不创建的条件.然后在这里 Enable_iff0(int x) {};,条件为false则没有类型.请注意,模板类是在开始时传递参数时实例化的,所做的只是将 T 替换为 void.

You mustn't use this way because your object will be created in any case since the class doesn't have a condition to be created or not. And then here Enable_if<false, T> f0(int x) {};, the condition is false then there is no type. note that template class is instantiated on passing your parameter in the beginning and all that has done is replacing T by void.

您可以使用的一种方法如下

one way you can use is as follows

#include <type_traits>
using namespace std;

template<bool B, typename T>
using Enable_if = typename std::enable_if<B,T>::type;


struct X {
    template <class T>
    Enable_if<true, T> f0(int x) {}
    template <class T>
    Enable_if<false, T> f0(int x) {}
};

int main(void)
{
    X xx;
    xx.f0<void>(4);
    return 0;
}

这里我们有两个函数模板,因此它们中的每一个都可以被实例化,也可以不被实例化,这取决于类内部的条件.如果为真,函数将被实例化,反之亦然.注意这里只实例化了需要的函数.

Here we have two function templates, hence each one of them may be instantiated or not and this depends on the condition inside the class. If it's true, the function will be instantiated and vice versa. note that here only the needed function is instantiated.

这篇关于使用 enable_if 来防止声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆