为什么使用enable

编程入门 行业动态 更新时间:2024-10-20 03:32:42
本文介绍了为什么使用enable_if编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么这不能与gcc48和clang32一起编译?

Why this does not compile with gcc48 and clang32?

#include <type_traits> template <int N> struct S { template<class T> typename std::enable_if<N==1, int>::type f(T t) {return 1;}; template<class T> typename std::enable_if<N!=1, int>::type f(T t) {return 2;}; }; int main() { S<1> s1; return s1.f(99); }

GCC错误:

/home/lvv/p/sto/test/t.cc:12:2: error: no type named ‘type’ in ‘struct enable_if<false, int>’ f(T t) {return 2;}; ^

CLANG错误:

/home/lvv/p/sto/test/t.cc:11:26: error: no type named 'type' in 'std::enable_if<false, int>'; 'enable_if' cannot be used to disable this declaration typename std::enable_if<N!=1, int>::type ^~~~ /home/lvv/p/sto/test/t.cc:16:7: note: in instantiation of template class 'S<1>' requested here S<1> s1; ^

编辑-解决方案

我已经接受了Charles Salvia的回答,但是出于实际原因,我无法使用建议的解决方法(专门针对N).我找到了其他对我有效的解决方法.使enable_if依赖于T:

I've accepted answer from Charles Salvia, but for practical reasons I was not able to use workaround that was proposed (specialize on N). I found other workaround which works for me. Make enable_if depend on T:

typename std::enable_if<(sizeof(T),N==1), int>::type

推荐答案

因为您使用enable_if而不在功能模板中使用模板参数T.如果要在结构S具有特定模板参数值N时进行专业化,则需要使用类模板专业化.

Because you use enable_if without using the template parameter T in your function templates. If you want to specialize for when the struct S has a certain template parameter value N, you'll need to use class template specialization.

template <int N, class Enable = void> struct S { }; template <int N> struct S<N, typename std::enable_if<N == 1>::type> { .... };

更多推荐

为什么使用enable

本文发布于:2023-11-09 21:03:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:enable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!