C++ C++;在接受派生类对象的派生类中强制执行函数

C++ C++;在接受派生类对象的派生类中强制执行函数,c++,inheritance,C++,Inheritance,我希望从基类派生的所有类都具有此函数: class Derived : public Base{ public: void doSth(const Derived& d){ ... } } 这可以在我的基类中强制执行吗 class Base{ public: virtual void doSth(const Base& b) = 0; // ? } 不,虚拟函数没有帮助,因为您更改了它的签名。 下面是一个可能依赖C++11特性的实现。

我希望从基类派生的所有类都具有此函数:

class Derived : public Base{
public:
    void doSth(const Derived& d){
        ...
    }
}
这可以在我的基类中强制执行吗

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

不,虚拟函数没有帮助,因为您更改了它的签名。 下面是一个可能依赖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.");
  }
};
#包括
模板
结构具有_doSth{
静态断言(
std::整型_常量::值,
“第二个模板参数必须是函数类型。”);
};
//进行检查的专用化
模板
结构具有_doSth{
私人:
模板
静态constexpr自动检查(T*)
->字体名
std::是一样的吗<
decltype(std::declval().doSth(std::declval()),
无效的
>::type;//尝试调用它并查看返回类型是否正确
模板
静态constexpr std::false_类型检查(…);
typedef decltype(检查(0))类型;
公众:
静态constexpr bool value=type::value;
};
模板
阶级基础{
公众:
Base(){
静态_断言(具有_doSth::value,“在派生类中缺少必需的函数”);
}
};
用法:

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

class BadDerived : public Base<BadDerived> {
public:
  void doSth(int d){
      ...
  }
};
类派生:公共基{
公众:
空隙度(常数和d){
...
}
};
类:公共基{
公众:
无效数据(内部数据){
...
}
};

没有。基类不能强制派生类实现任何非纯方法。而且,即使是纯方法也不需要实现,除非派生类的实例实际得到实例化。这太棒了!正是我想要的。