Public 继承的静态断言

Static Assert for Public Inheritance

我构建了一个助手class,它可以通过模板构建自定义class,这个自定义class必须继承自某个class,我可以检查一下std::is_base_of.

但是我还需要检查继承是public,如何实现?

作为参考,这是 class 的精简版,我在里面有 std::is_base_of

template<class CustomSink>
class Sink
{
    static_assert(std::is_base_of<BaseSink, CustomSink>::value, "CustomSink must derive from BaseSink");
    //Some static assert here to check if custom sink has publicly inherited BaseSink 
    //static_assert(is_public.....
public:
    template<class... Args>
    Sink(Args&&... args)
    {
    }
    ~Sink()
    {
    }       
};

据我所知,public继承是唯一可以执行隐式指针转换的情况(可以通过重载运算符实现引用转换)。

template <class T>
std::true_type is_public_base_of_impl(T*);

template <class T>
std::false_type is_public_base_of_impl(...);

template <class B, class D>
using is_public_base_of = decltype(is_public_base_of_impl<B>(std::declval<D*>()));

See it live on Coliru

感谢两个 Quentin and cpplearner for pointing me in the right direction. I found Quentins 如果断言应该通过,答案工作正常,但在失败的情况下 static_assert 不会捕获错误,而是在模板内生成,删除清晰 static_assert 消息的好处。

然后cpplearner提到了std::is_convertible,我以前尝试使用但忘记了需要*,而且B和D似乎是错误的。

所有这些让我创造了:

static_assert(std::is_convertible<Derived*, Base*>::value, "Derived must inherit Base as public");

这似乎可以完成工作,下面是作为完整示例的完整代码。

#include <type_traits>

class Base { };
class Derived : Base { };
class DerivedWithPublic : public Base { };

int main() {
    static_assert(std::is_convertible<DerivedWithPublic*, Base*>::value, "Class must inherit Base as public");
    static_assert(std::is_convertible<Derived*, Base*>::value, "Derived must inherit Base as public");
}