Container for a templated class
Sep 27, 2020 at 11:33am Sep 27, 2020 at 11:33am UTC
Hi
Suppose I have a templated class like this:
1 2 3 4 5 6 7 8 9 10 11 12
template <typename T>
class MyTemplate {
private :
T thing;
int num;
public :
MyTemplate(T t, int i) : thing(t), num (i) {}
};
I would like to have a container class which will have a member of type MyTemplate<T>. Is this just a matter of making the container class templated as well:
1 2 3 4 5 6 7 8 9 10 11 12
template <typename T>
class Container {
private :
bool someOtherMember = false ;
MyTemplate <T> element;
public :
Container(MyTemplate <T> t_element) : element(t_element) {}
};
I think this is the correct approach but grateful for any thoughts.
Thanks
Sep 27, 2020 at 12:36pm Sep 27, 2020 at 12:36pm UTC
You'd probably want the arguments of MyTemplate and Container passed by const ref so that a copy isn't made.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
template <typename T>
class MyTemplate {
private :
T thing;
int num;
public :
MyTemplate(const T& t, int i) : thing(t), num(i) {}
};
template <typename T>
class Container {
private :
bool someOtherMember = false ;
MyTemplate <T> element;
public :
Container(const MyTemplate <T>& t_element) : element(t_element) {}
};
// ....
// Below OK depending upon version of C++! Argument deduction has changed between versions.
MyTemplate<double > t1 {3.1, 2};
Container<double > my1 {t1};
Container<double > my2 {{3.1, 2}};
MyTemplate t2 {4.2, 5};
Container my3 {t2};
Container my4 {MyTemplate{4.5, 6}};
Sep 27, 2020 at 1:09pm Sep 27, 2020 at 1:09pm UTC
This is an xy problem:
http://xyproblem.info/
Please explain the problem that you're trying to solve rather than asking about the solution that you've come up with.
Sep 27, 2020 at 1:29pm Sep 27, 2020 at 1:29pm UTC
@dhayden - i've already explained the problem. what is the best way to design a container for a templated class? honestly, why do people get so pissy about things. say something nice or don't say anything at all.
Topic archived. No new replies allowed.