#include #include // for min() #include using namespace std; // ====================================================================== // template de classe template class mathvector { public: // ---------------------------------------- // constructeurs mathvector(array init) : content_(init) {} // remet le constructeur par défaut, avec zero-initialization mathvector() : content_{} {} // ---------------------------------------- void display(ostream& out) const { out << "( "; if (dim > 0) { constexpr size_t last(dim - 1); for (size_t i(0); i < last; ++i) out << content_[i] << ", "; out << content_[last]; } out << " )"; } // ---------------------------------------- mathvector operator+(mathvector const& other) const { mathvector retour(*this); for (size_t i(0); i < dim; ++i) retour.content_[i] += other.content_[i]; return retour; } // ---------------------------------------- mathvector& operator*=(T x) { for (auto& el : content_) el *= x; return *this; } // ---------------------------------------- // méthode template (de classe template !!) template mathvector convert() const { array init{}; constexpr size_t lower(min(dim, dim2)); for (size_t i(0); i < lower; ++i) init[i] += content_[i]; return mathvector(init); } // ---------------------------------------- private: array content_; }; // ====================================================================== // template de fonctions template ostream& operator<<(ostream& out, mathvector vect) { vect.display(out); return out; } // ---------------------------------------- template mathvector operator*(T x, mathvector vect) { return vect *= x; } // ====================================================================== int main() { mathvector<2> v1({3.4, 4.5}); mathvector<4, int> v2({3, 4, 5, 6}); /* L'instantiation implicite (de convert) ne fonctionne pas * car rien dans l'expression DE L'APPEL ne permet de déduire le * type de retour voulu (quelle dimension ?). */ // mathvector<3, int> v3(v2.convert()); // mathvector<4, double> v4(v1.convert()); mathvector<3, int> v3(v2.convert<3>()); mathvector<4> v4(v1.convert<4>()); cout << mathvector<3>() << endl; // default ctor cout << v1 << endl; cout << v2 << endl; cout << v3 << endl; cout << v4 << endl; cout << -2 * v2 << endl; cout << v3 + v3 << endl; return 0; }