簡體   English   中英

派生類中的C ++ Enforce函數接受派生類的對象

[英]C++ Enforce function in derived class that accepts an object of the derived class

我希望從我的基類派生的所有類都具有以下功能:

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.");
  }
};

用法:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM