SFINAE 中未继承类型以进行多重继承?

发布于 2024-12-09 03:29:36 字数 1307 浏览 3 评论 0原文

我正在使用 SFINAE 机制来推断类型。如果 class T 不包含 yes 并且被推导,则 Resolve::type 被推导为 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 <----

根据以下逻辑,上述测试的结果应该是:

  1. Resove::type = MyClass
  2. Resove::type = MyClass
  3. 解析::type = D1
  4. 解析::type = MyClass
  5. 解决::type = MyClass编译器错误(由于B1、B2之间的歧义)

奇怪的是,在测试用例(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:

  1. Resove<B1>::type = MyClass
  2. Resove<B2>::type = MyClass
  3. Resove<D1>::type = D1
  4. Resove<D2>::type = MyClass
  5. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与清晨阳光 2024-12-16 03:29:36

为什么会出现编译器错误?您知道 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 by D3 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文