c++c++11templatescastingboost-signals2

Cast return value to templated type


I have the following template class.

template<typename T, typename R = void> 
class Event 
{ 
 public:  
  typedef boost::signals2::signal<R (const T&)> signal_t;

  virtual R fire(const T& argument)   
  {
    return static_cast<R>(*signal_(argument));   
  }    

private:
  signal_t signal_;

   ...    
};

Since R can be void I get an invalid indirection compile error on line

return static_cast<R>(*signal_(argument));   

It seems it cannot be solved by a run-time check, since it is a template class. One cannot return "type" void. How can I resolve this?


Solution

  • You can try to specialize the template something like this:

    template<typename T>
    class Event<T,void>
    {
      typedef boost::signals2::signal<void (const T&)> signal_t;
      virtual void fire(const T& argument)   
      {
        signal_(argument);   
      }    
    private:
      signal_t signal_;
    
       ...    
    };
    

    So, we replaced R with explicit "void" value thus we can see the places that are ridiculous or redundant from the C++ compiler viewpoint. In your case, it's just a signal call without returning a value. In more sophisticated scenarios, you may need to re-compose bigger part of the code dependent on "R".