【问题标题】:Template assertion in C++?C ++中的模板断言?
【发布时间】:2010-01-28 04:49:12
【问题描述】:

有没有办法定义模板

assertInheritsFrom<A, B>

这样

assertsInheritsFrom<A, B>

当且仅当编译

class A : public B { ... } // struct A is okay too

谢谢!

【问题讨论】:

  • 附注:templates(带有尾随 s)是更常见的标签。
  • 好的;公认。不会回滚。

标签: c++ inheritance templates


【解决方案1】:

将静态断言与来自 Boost.TypeTraits 的 is_base_of&lt;Base,Derived&gt; 结合起来:

BOOST_STATIC_ASSERT(boost::is_base_of<B, A>::value);

一个简单的实现(不考虑整数类型、私有基类和歧义)可能如下所示:

template<class B, class D>
struct is_base_of {
    static yes test(const B&); // will be chosen if B is base of D
    static no  test(...);      // will be chosen otherwise
    static const D& helper();
    static const bool value = 
        sizeof(test(helper())) == sizeof(yes);
    // true if test(const B&) was chosen
};

【讨论】:

  • 您能解释一下这是如何工作的吗? (即is_base_of是如何实现的,有点超出我的理解)
  • Travis,这与答案中的链接相同,它实际上并没有解释它是如何工作的。检查代码也不一定能解释它。有时散文会有所帮助。但可能不适合 Stack Overflow cmets 的数量。 Anon,如果您尝试阅读代码但仍然不理解,请发布一个关于它的新问题。 (请注意,在 Boost 的 is_base_and_derived.hpp 中有一些解释,并附有一些链接。)
【解决方案2】:

您可以从 Alexandrescu 的书中阅读此部分 Detecting convertibility and inheritance at compile time

编辑:另外一个链接:http://www.ddj.com/cpp/184403750寻找检测可转换性和继承

【讨论】:

  • 您能在这里提供一个摘要吗? Google 只会如此频繁地提供一本书,然后它会在一段时间内屏蔽其他所有人。
【解决方案3】:

您可能还想阅读 Bjarne Stroustrup 的 C++ 常见问题解答中的此条目:Why can't I define constraints for my template parameters?(答案是可以,他提供了如何实现 Derived_from 约束的示例。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多