beng

Perfect forwarding to virtual method

May 15th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <utility>
  3.  
  4. void doStuff(int* i) { }
  5.  
  6. template<typename... Args>
  7. struct Consumer {
  8.   virtual void ConsumeImpl(Args*... args) {
  9.     doStuff(*args...);
  10.   }
  11.  
  12.   template<typename... Args1>
  13.   void Consume(Args1&&... args) {
  14.     ConsumeImpl(&args...);
  15.   }
  16. };
  17.  
  18. template<typename... Args>
  19. void forwardToConsumer(Args&&... args) {
  20.   Consumer<typename std::decay<Args>::type...> p;
  21.   p.Consume(std::forward<Args>(args)...);
  22. }
  23.  
  24. int main() {
  25.   int i = 1;
  26.   int * const iPtr = &i;
  27.  
  28.   // This does not compile. Error:                                                                                                          
  29.   // foo.cc: In instantiation of ‘void Consumer<Args>::Consume(Args1&& ...) [with Args1 = {int* const&}; Args = {int*}]’:                    
  30.   // foo.cc:21:3:   required from ‘void forwardToConsumer(Args&& ...) [with Args = {int* const&}]’                                          
  31.   // foo.cc:29:25:   required from here                                                                                                      
  32.   // foo.cc:14:5: error: invalid conversion from ‘int* const*’ to ‘int**’ [-fpermissive]                                                    
  33.   // foo.cc:8:16: error:   initializing argument 1 of ‘void Consumer<Args>::ConsumeImpl(Args* ...) [with Args = {int*}]’ [-fpermissive]      
  34.   forwardToConsumer(iPtr);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment