Specyfikacje szablonów z 2 parametrami

0

Cześć,

na początek fragment kodu:

class Foo {
public:
    
    template<typename Type>
    Type get();
    
private:
    int value = 10;
    
};

template<>
int Foo::get(){
    return value;
}

template<>
string Foo::get(){
    return to_string(value);
}

//**************************************

class Bar {
public:
    
    template<typename Type>
    Type get();
    
private:
    int value = 15;
};

template<>
int Bar::get(){
    return value;
}

template<>
string Bar::get(){
    return to_string(value);
}

//**************************************

class Elo {
public:
    
    template<typename Type>
    Type get();    
    
private:
    Foo foo;
    Bar bar;
    
};

template<>
int Elo::get(){
    return foo.get<int>();
}

template<>
string Elo::get(){
    return foo.get<string>();
}

template<>
int Elo::get(){
    return bar.get<int>();
}

template<>
string Elo::get(){
    return bar.get<string>();
}

A teraz pytanie, w jaki sposób mogę tak napisać specjalizację szablonowej metody get() w klasie Elo, aby w zależności od podanych parametrów wywołała się metoda get() z klasy Bar lub klasy Foo?

Czyli coś takiego, by mnie interesowało:

elo.get<string, Bar>();
elo.get<int, Foo>();
0

Jeżeli to ci się nie spodoba:

#include <iostream>
#include <string>
using namespace std;

class Foo 
  {
   public: 
   template<typename Type> Type get();
   private:
   int value=10; 
  };
 
template<> int Foo::get() { return value; }
template<> string Foo::get() { return to_string(value); }
 
class Bar 
  {
   public:
   template<typename Type> Type get();
   private:
   int value=15;
  };
 
template<> int Bar::get() { return value; } 
template<> string Bar::get() { return to_string(value); }

class Elo
  {
   public:
   template<typename Type,bool F> Type get(); 
   private:
   Foo foo;
   Bar bar;
  };
 
template<> int Elo::get<int,true>() { return foo.get<int>(); }
template<> string Elo::get<string,true>() { return foo.get<string>(); }
template<> int Elo::get<int,false>() { return bar.get<int>(); } 
template<> string Elo::get<string,false>() { return bar.get<string>(); }

int main()
  {
   Elo e;
   cout<<e.get<int,false>()<<endl;
   cout<<e.get<int,true>()<<endl;
   return 0;
  }

to jedynym rozwiązaniem jest dziedziczenie po Bar i Foo

0

@nz dokładnie o takie coś mi chodziło, dzięki.
@_13th_Dragon dzięki za wskazówki również, docelowo będzie więcej klas niż dwie więc rozwiązanie z true i false odpada, dziedziczenie jeszcze przemyślę czy nie byłoby dobrym wyborem.

1 użytkowników online, w tym zalogowanych: 0, gości: 1