From 0e26332bfb379a946c4774aa96d81e110071abb5 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 4 Feb 2020 17:20:17 +0100 Subject: fix: improve template security with its specialization --- I_anno/Programmazione_1/lab_14_12_18.cc | 41 +++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/I_anno/Programmazione_1/lab_14_12_18.cc b/I_anno/Programmazione_1/lab_14_12_18.cc index 527da64..02bbd69 100644 --- a/I_anno/Programmazione_1/lab_14_12_18.cc +++ b/I_anno/Programmazione_1/lab_14_12_18.cc @@ -58,31 +58,54 @@ private: }; template -class C : public A { +class C; + +template<> +class C : public A { public: C(short n) : A{n} { - if(typeid(T) == typeid(short)) { - x = g(n); - } else { - x = static_cast(log(1+n)); - } + x = static_cast(log(1+n)); + } + + double foo(short r) const { + return g(r*x); + } + + double g(double k) const { + return 3*k; + } + + void print(ostream& os) { + os << "C "; + getPtr(os); + os << ", x=" << x; + } +private: + short x; +}; + +template<> +class C : public A { +public: + C(short n) : A{n} { + x = g(n); } double foo(short r) const { return g(r*x); } - T g(T k) const { + short g(short k) const { return 3*k; } void print(ostream& os) { - os << "C<" << typeid(T).name() << "> "; + os << "C "; getPtr(os); os << ", x=" << x; } private: - T x; + short x; }; ostream& operator<<(ostream& os, A& a) { -- cgit v1.2.3-18-g5258