3

The concept of variadic templates is quite confusing to me and I want to make it a bit more complex (well I think...).
Let us consider the following code:

template <typename T>
class base  
{  
    template <typename... E>  
    virtual void variadic_method_here(E... args) = 0;  
};

and an implementing class:

class derive : public base<some_object> 
{  
    void variadic_method_here(concrete_args_here);  
};

How do I do that?

4
  • 8
    As far as I know, templates can't be virtual, variadic or not. Commented Oct 2, 2011 at 13:29
  • @pmr - wasn't aware that I can do that. I almost never read faq's and getting started guides. Thnx =) Commented Oct 2, 2011 at 14:23
  • 1
    @RoyiFreifeld That might as well explain why you try to do something the language does prohibit. :) Commented Oct 2, 2011 at 15:00
  • @pmr - Nah... That's just lack of knowledge, or the need to use this "dark side" of C++. Commented Oct 2, 2011 at 19:18

2 Answers 2

4

I think if I were faced with this problem I'd use CRTP and overloads to solve the problem.

e.g.:

#include <iostream>

template <typename Impl>
class base {
public:
   template <typename... E>
   void foo(E... args) {
      Impl::foo_real(args...);
   }
};

class derived : public base<derived> {
public:
   static void foo_real(double, double) {
     std::cout << "Two doubles" << std::endl;
   }

   static void foo_real(char) {
     std::cout << "Char" << std::endl;
   }
};

int main() {
  derived bar;
  bar.foo(1.0,1.0);
  bar.foo('h');
}
Sign up to request clarification or add additional context in comments.

6 Comments

Which still leaves the problem of runtime-polymorphism OP is apparently aiming for.
@pmr - They don't specifically ask for runtime polymorphism - to me it seemed like they wanted compile time polymorphism but didn't know about CRTP
You could be right. The virtual in OPs code could be a not-so-concious decision.
@awoodland - You're right. I never heard about CRTP and it sounds like a good idea, but I'm still not sure it will solve my problem. The derived class might be decided by some clicks on GUI of my application. Will it work if I have 2 or more derived classes?
@RoyiFreifeld - sounds like you want runtime polymorphism then if there's more than 1 derived class in use in your application. The problem with template virtual functions is how does the compiler decide which types to instantiate for? There's no reason to assume that where the compiler sees the call and where it's implemented are in the same translation unit, so figuring out which variants to instantiate in derived classes is (in general) impossible for the compiler.
|
4

You can't have a templated virtual function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.