#include #include // for min() #include using namespace std; // ====================================================================== // template de classe template class mathvector { public: // ---------------------------------------- // constructeurs mathvector(array values) : content_(values) {} // remet le constructeur par défaut mathvector() : content_{} // zero initialization {} // ---------------------------------------- void display(ostream& out) const { out << "( "; if (size > 0) { constexpr size_t last(size - 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 < size; ++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(size, size2)); for (size_t i(0); i < lower; ++i) init[i] += content_[i]; return mathvector(init); } private: array content_; }; // ====================================================================== // template de fonction template ostream& operator<<(ostream& out, mathvector const& vec) { vec.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}); cout << mathvector<3>() << endl; // default ctor cout << v1 << endl; cout << v2 << endl; cout << -2 * v2 << endl; cout << v2 + v2 << endl; // L'instantiation implicite (de convert) ne fonctionne pas... /* Il faut une instantiation explicite (parce qu'en C++ le type * de retour ne fait pas partie de l'identification de la fonction, * donc 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<3>()); mathvector<4, double> v4(v1.convert<4>()); cout << v3 << endl; cout << v4 << endl; // cout << v3 + v3 << endl; return 0; }