Reputation: 574
I want to implement a function like this:
template <class C>
C string_to_number(const string &s){
stringstream ss(s);
C num;
ss >> num;
return num;
}
but it cause error. I can do this without class C
but only one data type like double string_to_number(const string &s)
or int string_to_number(const string &s)
but I can't have both at the same time.
How can I do this to use the function like this:
int main()
{
string s = "12.75";
double d = string_to_number(s); // be 12.75
int i = string_to_number(s); // be 12
}
anybody knows there is any way to do it ?
Upvotes: 2
Views: 940
Reputation: 7491
Return type deduction can be emulated via user-defined conversion operators:
#include <sstream>
#include <string>
class string_to_number final
{
public:
string_to_number(const std::string& string)
: string_{string}
{
}
string_to_number(const string_to_number&) = delete;
template <class Type>
operator Type() const &&
{
std::stringstream string_stream{string_};
Type value;
string_stream >> value;
return value;
}
private:
const std::string& string_;
};
// ...
std::string s = "12.75";
double d = string_to_number(s); // be 12.75
int i = string_to_number(s); // be 12
Upvotes: 1
Reputation: 173044
The template parameter C
is only used as the type of function return value, not function parameter, it can't be deduced.
When possible, the compiler will deduce the missing template arguments from the function arguments.
You have to specify the template argument explicitly, e.g.
double d = string_to_number<double>(s); // be 12.75
int i = string_to_number<int>(s); // be 12
Upvotes: 1
Reputation: 7601
Take this line
double d = string_to_number(s); // be 12.75
The compiler has to instantiate the function template string_to_number
. For deduction of the template argument, there is neither an explicit template parameter list, nor function parameters to deduce from. Apart from that, there is no other mechanism for deducing template parameters. Especially return values will not be considered for template argument deduction, as your code wants to suggest.
As the function argument does not carry any dependency on the template parameter, you have to specify the explicit template parameter:
double d = string_to_number<double>(s); // be 12.75
And thanks to auto
, you can remove the redundancy:
auto d = string_to_number<double>(s); // be 12.75
Upvotes: 0