多态,可变参数模板继承,切片,boost ::任何类型转换

时间:2015-02-23 16:56:51

标签: c++ polymorphism variadic-templates boost-any

这个程序编译,但是boost :: any cast失败了。我怀疑以这种方式切片模板会混淆指针算法。想法是存储在容器中的内容

std::vector<boost::any> pressures;

属于不同类型,例如

Pressure<Printer>, or Pressure<Printer, Printer> etc.

由于我通过将其存储在boost :: any中而丢失了类型,因此我需要调用Change而不必知道给定压力下的实际观察者数量。我试图通过多态和虚方法解决它,但至少这种尝试不起作用。

有什么建议吗?

#include <utility>
#include <tuple>
#include <iostream>

enum class EventType {UNKNOWN};


// Note: All Observers must implement OnNotify for any subject types they wish to observe
//       Any unimplemented subject types that are used will result in a compiler error
template <typename Base> class Observer
{
public:
    Observer() : obsID_(obsIDTracker_++) {}
    template <typename T> void OnNotifyImpl(T &subject, EventType event)
    {
        static_cast<Base *>(this)->OnNotify(subject, event);
    }
    int GetID() const
    {
        return obsID_;
    }
private:
    int obsID_;
    static int obsIDTracker_;
};
template <typename base> int Observer<base>::obsIDTracker_ = 0;

// Recursive helper structs for implementing calls to all observers held within subjects
template <int N, typename T, typename... Args> struct NotifyHelper
{
    static void NotifyImpl(T &subject, EventType event,
                           std::tuple<Args...> &obs)
    {
        std::get<sizeof...(Args) - N>(obs).OnNotifyImpl(subject, event);
        NotifyHelper<N - 1, T, Args...>::NotifyImpl(subject, event, obs);
    }
};
template <typename T, typename... Args> struct NotifyHelper<0, T, Args...>
{
    static void NotifyImpl(T &subject, EventType event,
                           std::tuple<Args...> &obs) {}
};

// See MakeSubject function for instance usage
template <typename T, typename... Obs> class Subject
{
public:
    static const int NumberOfObservers = sizeof...(Obs);
    Subject(std::tuple<Obs &...> &&obs) : observers(obs) {}
    void NotifyAll(EventType event)
    {
        NotifyHelper<NumberOfObservers, T, Obs &...>::NotifyImpl(
            *static_cast<T *>(this), event, observers);
    }

private:
    std::tuple<Obs &...> observers;
};

class PressureInterface
{
public:
    virtual ~PressureInterface() {}
    virtual void Change(int value) {}
};

// CRTP Abstract Base class for implementing static subject.
// Example Subclass Usage -- Pressure Sensor:
template <typename... Obs>
class Pressure : public PressureInterface, public Subject<Pressure<Obs...>, Obs...>
{
public:
    typedef Subject<Pressure<Obs...>, Obs...> BaseType;
    Pressure(std::tuple<Obs &...> &&observers, int pressure)
        : BaseType(std::move(observers)), pressure_(pressure) {}
    virtual void Change(int value)
    {
        pressure_ = value;
        this->NotifyAll(EventType::UNKNOWN);
    }
    int GetPressure() const
    {
        return pressure_;
    }

private:
    int pressure_;
};

// CRTP Abstract Base class for implementing static subject.
// Example Subclass Usage -- Printing Observer:
class Printer : public Observer<Printer>
{
public:
    Printer() : timesTriggered_(0) {}
    template <typename... Args>
    void OnNotify(Pressure<Args...> &subject, EventType event)
    {
        std::cout << "Observer ID: " << this->GetID() << std::endl;
        switch (event)
        {
        case EventType::UNKNOWN:
        {
            std::cout << "Unknown Event -- Event #" << timesTriggered_++
                      << std::endl;
            std::cout << "Pressure: " << subject.GetPressure() << std::endl;
            break;
        }
        default:
        {
            break;
        }
        }
    }

private:
    int timesTriggered_;
};


// Binding function for use with MakeSubject
//   Arguments: observer objects to observe subject notifications
//   Return:    tuple of references to observers
template <typename... Obs> std::tuple<Obs &...> BindObservers(Obs &... obs)
{
    return std::tuple<Obs &...>(obs...);
}

// Creator to ease subject creation
//   Template Arguments: Subject subclass type
//   Arguments: Result from BindObservers
//              Any constructor arguments for Subject subclass
//   Return:    Subject subclass
// Example Usage:
// auto pressure = MakeSubject<Pressure>(BindObservers(printerObs), initialPressure);
template <template <typename...> class T, typename... Args, typename... Obs>
T<Obs...> MakeSubject(std::tuple<Obs &...> &&obs, Args &&... args)
{
    return T<Obs...>(std::move(obs), args...);
}

#include <boost/any.hpp>

int main()
{
    std::vector<boost::any> pressures;

    Printer printerObs1;
    Printer printerObs2;

    const int initialPressure = 1;

    auto pressure = MakeSubject<Pressure>(
                        BindObservers(printerObs1, printerObs2), initialPressure);

    pressures.push_back(pressure);

    pressure.Change(12);

    decltype(pressure) *p = boost::any_cast<decltype(pressure)>(&pressures[0]);

    p->Change(1999);

    PressureInterface *qip = boost::any_cast<PressureInterface>(&pressures[0]); //This cast returns nullptr

    std::cout << "The cast works\n";

    if(nullptr != qip) 
        qip->Change(2001);
}

修改

我第一次尝试存储更改功能的地址:

std::vector<std::function<boost::any *>> pressures;

如何push_back函数的地址?这不起作用:

pressures.push_back(std::function<decltype(&pressure.Change>);

/home/idf/Documents/OrigObserverExam/ObserverExample.cpp|157|error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&Pressure<Printer, Printer>::Change' [-fpermissive]|

然后如何提取它?

std::function<void(int)> *qip = boost::any_cast<std::function<void(int)>*>(&(pressures[0].Change));

std::cout << "The cast works\n";

if(nullptr != qip)
    *qip(2001);

修改2

当我添加建议的代码时,我收到错误:

/home/idf/Documents/OrigObserverExam/ObserverExample.cpp|167|error: 'decay_t' is not a member of 'std'|

#include <type_traits>
#include <boost/any.hpp>

struct changable {
  boost::any data;
  using do_change = void(*)(boost::any*, int);
  do_change f = nullptr;
  void change(int x) {
    if (f) f(&data, x);
  }
  template<class T>
  static do_change type_erase_change() {
    return [](boost::any* a, int x){
      T* t = boost::any_cast<T>(a);
      if (t) t->Change(x);
    };
  }
  template<class T>
  changable( T&& t ):
    data(std::forward<T>(t)),
    f( type_erase_change<std::decay_t<T>>() )
  {}
  changable(changable const&)=default;
  changable(changable &&)=default;
  changable()=default;
};

编辑3 安装了C ++ 14:

如何使用此结构?我可以说:

 std::vector<changable> pressures;

我能够推迟压力

pressures.push_back(pressure);

然而,我不确定如何称呼压力[0] .Change(1999)。如果我说我得到错误:

pressures[0].Change(2000); 

ObserverExample.cpp|199|error: '__gnu_cxx::__alloc_traits<std::allocator<changable> >::value_type' has no member named 'Change'

1 个答案:

答案 0 :(得分:2)

boost::any允许您键入强制转换为您输入的完全相同的类型。不是父类型,相同的类型。

如果要键入erase调用方法,请尝试std::function<void()>std::function<void(boost::any*)>

以下是捆绑在一起的change(int)boost::any类型的橡皮擦:

struct changable {
  boost::any data;
  using do_change = void(*)(boost::any*, int);
  do_change f = nullptr;
  void change(int x) {
    if (f) f(&data, x);
  }
  template<class T>
  static do_change type_erase_change() {
    return [](boost::any* a, int x){
      T* t = boost::any_cast<T>(a);
      if (t) t->Change(x);
    };
  }
  template<class T>
  changable( T&& t ):
    data(std::forward<T>(t)),
    f( type_erase_change<std::decay_t<T>>() )
  {}
  changable(changable const&)=default;
  changable(changable &&)=default;
  changable()=default;
};

不需要公开Change的接口类。只要传递给上述类型橡皮擦的类型采用Change(int)方法,一切都很好。