Oto kod opisujący problem, z którym się zmagałam. Ostatnim problemem (o ile dotyczy to g ++) jest: "błąd:" Foo-T "nie został zadeklarowany w tym zakresie" podczas wykonywania procedury konstruktora Bar :: Bar (...). W przeciwnym razie problem, którego próbuję się nauczyć, polega na ustawianiu typów elementów bazowych na podstawie argumentów przekazywanych do konstruktora klasy pochodnej za pomocą szablonów. Jeśli byłby sposób na ustawienie typu członka klasy podstawowej (T Foo-T) po prostu przekazując argumenty do konstruktora klasy pochodnej, wolałbym to. W chwili obecnej nie widzę sposobu przeszłego używania zarówno argumentu szablonu, jak i zgodnego argumentu konstruktora klasy pochodnej, aby wykonać to zadanie. Czy potrafisz dostrzec cokolwiek w poniższym kodzie, że mogę robić lepiej, aby osiągnąć te same cele? Jestem raczej nowy w generycznym kodowaniu i szablonach.Inicjowanie podstawowych typów elementów szablonu w listach inicjalizujących klasy pochodnej
#include <iostream>
typedef int a_arg_t;
typedef double b_arg_t;
typedef std::string foo_arg_t;
class TypeA {
public:
TypeA();
TypeA (a_arg_t a) {
/* Do sosmething with the parameter passed in */
}
};
class TypeB {
public:
TypeB();
TypeB (b_arg_t b) {
/* typeB's constructor - do something here */
}
};
// The base-class with a member-type to be determined by the template argument
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) // initialize something here
{
/* do something for foo */
}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
// the derived class that should set the basse-member type (T Foo_T)
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
// the initialization of Foo_T has to be done outside the initializer list because it's not in scsope until here
Foo_T = TypeA(a_arg); // if an a_arg_t is passed in, then we set the Foo_T to TypeA, etc.
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo_T = TypeB(b_arg);
}
};
int main() {
b_arg_t b_arg;
a_arg_t a_arg;
foo_arg_t bar_arg;
Bar<TypeA> a (bar_arg, a_arg); // try creating the derived class using TypeA
Bar<TypeB> b (bar_arg, b_arg); // and another type for show
return 0;
}
Uwaga: domyślne konstruktory na obiektach typu A i TypeB potrzebują ciał, w przeciwnym razie wystąpią błędy łącza. – csj