+ 1

Template Specialization code help

You are given a Div class template, which has a constructor that takes two parameters and outputs their division. You need to specialize the class for strings, which should output the division of the lengths of the parameter strings, as the division operator is not defined for strings. Create the template specialization so that the code in main executes correctly. #include <iostream> #include <string> using namespace std; template <class T> class Div { public: Div (T x, T y) { cout <<x / y<<endl; } }; //your code goes here template <> class Div <string>{ public: Div (string x, string y){ cout<<x/y<<endl; } }; int main () { string a, b; cin >> a >> b; int x, y; cin >> x >> y; Div <string> d2(a, b); Div <int> d1(x, y); }

28th Aug 2021, 1:23 AM
Kevin Truong
Kevin Truong - avatar
3 odpowiedzi
+ 5
#include <iostream> using namespace std; template <class T> class Div { public: Div (T x, T y) { cout <<x / y<<endl; } }; template <> class Div <string> { public: Div <string> (string x, string y) { cout <<x.length() / y.length()<<endl; } }; int main () { string a, b; cin >> a >> b; int x, y; cin >> x >> y; Div <string> d2(a, b); Div <int> d1(x, y); } Good Luck
26th Jan 2022, 5:46 AM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
+ 1
template<> class Div<string> { public: Div(string x, string y) { cout << strlen(x) / strlen(y) << endl; } };
28th Aug 2021, 10:18 AM
Roma Butaku
Roma Butaku - avatar