为什么我不能添加带有类型查找的抽象层来剥离C ++中的引用? [英] Why can't I add a layer of abstraction with type lookup to strip references in C++?

查看:92
本文介绍了为什么我不能添加带有类型查找的抽象层来剥离C ++中的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对以下问题的解答

为什么我不能在C ++中将特征与转发引用一起使用?

已正确回答。但是我在下面尝试了自己的解决方案

which has been correctly answered. However I tried my own solution below

https:// godbolt.org/z/X7dBz1

#include <type_traits>

template <typename T, typename enable = void> struct Traits {
    static const bool value = false;
};

template <typename T> struct Traits<T,std::enable_if<std::is_reference<T>::value>> {
    static const bool value = Traits<typename std::remove_reference<T>::type>::value;

};

struct Zip{};
template <> struct Traits<Zip,void> {
    static const bool value = true;
};

template <typename E>
void Execute(E && e){
    static_assert(Traits<E>::value);
}

int main(){
    auto z = Zip();
    Execute(z);
}

理论是,如果正确的专业化失败,那么下一个最专业的将是根据 T 是否作为参考进行匹配的一个。如果匹配,则删除引用,我们希望递归获得匹配。但这似乎不起作用。有没有办法解决这个问题,从而保持我的尝试精神?

the theory being that if the correct specialisation fails then the next most specialized will be the one that matches based on if T is a reference. If this matches then the reference is stripped and we recurse hopefully getting a match. But this does not seem to work. Is there a way to fix this that keep the spirit of my attempt?

推荐答案

您正在滥用 std :: enable_if 。如所写,您的 Traits 结构专门针对 std :: enable_if 本身,而不是其结果。您需要访问嵌套的 :: type 类型别名:

You are misusing std::enable_if. As written, your Traits struct is specialized on std::enable_if itself, not its result. You need to access the nested ::type type alias:

typename std::enable_if<std::is_reference<T>::value>::type
// or
std::enable_if_t<std::is_reference<T>::value>

godbolt.org上的实时示例

这篇关于为什么我不能添加带有类型查找的抽象层来剥离C ++中的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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