首页 > 解决方案 > 接受派生类对象的派生类中的 C++ 强制函数

问题描述

我希望从我的基类派生的所有类都具有此功能:

class Derived : public Base{
public:
    void doSth(const Derived& d){
        ...
    }
}

这可以在我的基类中强制执行吗?

class Base{
public:
    virtual void doSth(const Base& b) = 0;  // ?
}

标签: c++inheritance

解决方案


不,虚拟功能没有帮助,因为您更改了它的签名。这是一个依赖 C++11 特性的可能实现。它正确检测具有所需签名的功能。

#include <type_traits>


template<typename, typename T>
struct has_doSth {
    static_assert(
        std::integral_constant<T, false>::value,
        "Second template parameter needs to be of function type.");
};

// specialization that does the checking

template<typename C, typename Arg>
struct has_doSth<C, void(Arg)> {
private:
    template<typename T>
    static constexpr auto check(T*)
    -> typename
        std::is_same<
            decltype( std::declval<T>().doSth( std::declval<Arg>()) ),
            void
        >::type;  // attempt to call it and see if the return type is correct

    template<typename>
    static constexpr std::false_type check(...);

    typedef decltype(check<C>(0)) type;

public:
    static constexpr bool value = type::value;
};

template<typename T>
class Base {
 public:
  Base() {
    static_assert(has_doSth<T, void(const T&)>::value, "Missing required function in the derived class.");
  }
};

用法:

class WellDerived : public Base<WellDerived> {
public:
  void doSth(const WellDerived& d){
      ...
  }
};

class BadDerived : public Base<BadDerived> {
public:
  void doSth(int d){
      ...
  }
};

推荐阅读