+ 1

Template deduction without argument

I have two functions in class as int get() and void set(int). I need these two for double datatype as well. I can thought of these two as template functions but challenge is for get function. void set(T t) will have a parameter T inside function body which help me decide whether input is double or int using same_as from type_trait. What to be done for get function to know whether it is for int or double? Refer code below which solves purpose but is there a way which can avoid passing additional argument to get function?: #include <iostream> using namespace std; class test { public: test() {cout << "ctor\n";} template<class T> T get(T);//Originally it was int get(); template<class T> void set(T t);//Originally it was void set(int); }; template<class T> T test::get(T) {return 5.57;} template<class T> void test::set(T t) {} int main() { test obj = test(); cout << obj.get(1) << endl; cout << obj.get(1.1) << endl; return 0; }

2nd Mar 2024, 3:42 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 odpowiedzi
0
What will the be the type of the data when it is stored? What datatype you are returning for get() depends on how it is stored. The data should be able to switch from int to double depending on how it is initialized or set.
2nd Mar 2024, 11:31 PM
Bob_Li
Bob_Li - avatar
0
I don't need data conversion Bob_Li
3rd Mar 2024, 7:13 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I had a better version of this question at https://www.sololearn.com/Discuss/3267640/?ref=app
3rd Mar 2024, 7:27 AM
Ketan Lalcheta
Ketan Lalcheta - avatar