0

I have a template class

template <T>
class class1
{
    template< typename T1, typename T2>
   void func1 ()
   {  // do somthing }

   template< typename T1>
   void func2 ()
    { //do something }                                                     
};

class class2
{
     // Have three objects based on template type
     public:
     class2 ()
     {
         if (case1)
             obj = class1<type1> ;
         else if (case2) 
            obj = class1<type2>;
         else if (case3)
            obj = class1<type3>;
      }

       void fun1 ()
       { obj->func1(); }  //calling class1 function based on template type

        void func2 ()
       { obj->func2(); }  //

      typedef boost::variant <class1<Type1>, class1 <type2>, class1 <type3>> obj1;
      obj1 obj;

 };

How to call class1 functions using boost::variant. Can't create virtual class beacuse can't create templated virtual functions and I need to create a single object based on template type to avoid if else in each function.

Dodez
  • 19
  • 2
  • Is it normal that `func1`/`func2` are template ? if yes, with which type do you want to call them ? – Jarod42 Oct 11 '17 at 11:36
  • yes func1/func2 both are templates and it depends on runtime which function i cal based on arguments passed to main function – Dodez Oct 11 '17 at 11:47
  • template type can be anything, int, double, string or user defined class based on arguments passed on runtime – Dodez Oct 11 '17 at 11:48
  • In which cases you call `class1::func1()` or `class1::func1()` ? You have a variant which dictates on which instance to call a function, but you don't provide information to call the correct one. – Jarod42 Oct 11 '17 at 12:06
  • above mentioned code is just a sample, in actual code is more so i just pasted the sample of a portion where im facing the problem. – Dodez Oct 11 '17 at 12:18

1 Answers1

0

Use a visitor that takes any type (template operator()):

boost::apply_visitor([](auto& x){ x.func1(); }, obj);
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • Currently `class1::func1` is template (with non deducible types), so you have to provide them (but unclear from the OP what it should be :-/) – Jarod42 Oct 11 '17 at 11:38
  • class1::func1 is template (with non deducible types), types can be anything, it can be user defined classes also. – Dodez Oct 11 '17 at 11:53
  • @vittorio : Do i need to overload the operator() ? If yes, what do i need to add there. I want to call func1 and func2 from class2. nothing else – Dodez Oct 11 '17 at 11:55
  • @Dodez: no, the template `operator()` is generated for you by the *lambda expression*. – Vittorio Romeo Oct 11 '17 at 11:56
  • @VittorioRomeo in class2 void func1() { boost::apply_visitor([](auto& x){ x.func1(); }, obj); } is giving error of { } before compiling in the editor – Dodez Oct 11 '17 at 12:21
  • @Dodez: please post a [MCVE] of your code and an example of your desired behavior. – Vittorio Romeo Oct 11 '17 at 12:23