简体   繁体   中英

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM