SFINAE 中未继承类型以进行多重继承?
我正在使用 SFINAE 机制来推断类型。如果 class T
不包含 yes
并且被推导,则 Resolve
被推导为 T
如果包含 yes
,则为 MyClass
。
class MyClass {};
template<typename>
struct void_ { typedef void check; };
template<typename T, typename = void>
struct Resolve { typedef T type; };
template<typename T>
struct Resolve <T, typename void_<typename T::yes>::check> {
typedef MyClass type;
};
现在,我有简单的测试类,
struct B1 { typedef int yes; }; // 1
struct B2 { typedef int yes; }; // 2
struct D1 {}; // 3
struct D2 : B1 {}; // 4
struct D3 : B1, B2 {}; // 5 <----
根据以下逻辑,上述测试的结果应该是:
Resove
::type = MyClass Resove
::type = MyClass 解析
::type = D1 解析
::type = MyClass 解决
或编译器错误(由于B1、B2之间的歧义)::type = MyClass
奇怪的是,在测试用例(5)中它并没有发生。结果是,
Resolve<D3>::type = D3;
任何人都可以解释一下,多重继承有什么魔力吗?没有得到编译器错误是标准合规行为吗?这是演示。
I am using a SFINAE mechanism to deduce a type. Resolve<T>::type
is deduced to T
if class T
doesn't contain yes
and it's deduced to MyClass
if it contains yes
.
class MyClass {};
template<typename>
struct void_ { typedef void check; };
template<typename T, typename = void>
struct Resolve { typedef T type; };
template<typename T>
struct Resolve <T, typename void_<typename T::yes>::check> {
typedef MyClass type;
};
Now, I have the simple test classes as,
struct B1 { typedef int yes; }; // 1
struct B2 { typedef int yes; }; // 2
struct D1 {}; // 3
struct D2 : B1 {}; // 4
struct D3 : B1, B2 {}; // 5 <----
According to the logic following should be the result for above tests:
Resove<B1>::type = MyClass
Resove<B2>::type = MyClass
Resove<D1>::type = D1
Resove<D2>::type = MyClass
Resove<D3>::type = MyClass
or compiler error (due to ambiguity between B1, B2)
Strangely, in test case (5) it doesn't happen so. The result is,
Resolve<D3>::type = D3;
Can anyone explain, what magic is happening specially for multiple inheritance ? Not getting compiler error is a standard compliant behavior ? Here is the demo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么会出现编译器错误?您知道 SFINAE 代表
替换失败不是错误
吗?当您用
D3
替换T
时,表达式变得不明确。由于 SFINAE,这种失败不会被视为错误,您的专业化将被简单地从候选人中删除。这一切都是为了不得到编译器错误。Why would you expect a compiler error? You know SFINAE stands for
Substitution Failure Is Not An Error
right?When you substitute
T
byD3
the expression becames ambiguous. Due to SFINAE, this failure is not considered an error and your specialization is simply removed as a candidate. It's all about NOT getting a compiler error.