std::enable_if 专业化失败
我一直在摆弄enable_if,我似乎偶然发现了一些不一致的行为。这是VS2010中的。我已将其简化为以下示例。
#include <type_traits>
using namespace std;
// enable_if in initial template definition
template <class T, class Enable = enable_if<true>> struct foo {};
foo<int> a; //OK
// explicit specialisation
template <class T, class Enable = void> struct bar;
template <class T> struct bar<T, void> {};
bar<int> b; //OK
// enable_if based specialisation
template <class T, class Enable = void> struct baz;
template <class T> struct baz<T, std::enable_if<true>> {};
baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>'
这是代码或编译器中的错误吗?
I've been messing around with enable_if, and I seem to have stumbled upon some inconsistent behaviour. This is in VS2010. I've reduced it to the following sample.
#include <type_traits>
using namespace std;
// enable_if in initial template definition
template <class T, class Enable = enable_if<true>> struct foo {};
foo<int> a; //OK
// explicit specialisation
template <class T, class Enable = void> struct bar;
template <class T> struct bar<T, void> {};
bar<int> b; //OK
// enable_if based specialisation
template <class T, class Enable = void> struct baz;
template <class T> struct baz<T, std::enable_if<true>> {};
baz<int> c; //error C2079: 'c' uses undefined struct 'baz<T>'
Is this a bug in the code or the compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::enable_if
应该是typename std::enable_if::type
。std::enable_if
始终命名类型(std::enable_if
也是如此)。为了在条件为 false 时使替换失败,您需要使用type
嵌套 typedef,它仅在条件为 true 时定义。std::enable_if<true>
should betypename std::enable_if<true>::type
.std::enable_if<true>
always names a type (as doesstd::enable_if<false>
). In order to get substitution to fail when the condition is false you need to use thetype
nested typedef, which is only defined if the condition is true.您的问题与
enable_if
baz
此时的类型不完整无关。如果没有enable_if
,也会出现同样的问题:而且,正如 James 所说,您错误地使用了
enable_if
。 Boost 的enable_if
文档解释得很好。Your problem has very little to do with
enable_if
baz<int, void>
has an incomplete type at that point. The same problem will occur withoutenable_if
:And, as James said, you're using
enable_if
incorrectly. Boost's documentation forenable_if
does a great job explaining it.