Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function for a family of related functions (e.g. std::stoi, std::stof, std::stod etc)

Tags:

c++

templates

I'd like to make a generic function for std::stoi, std::stof, std::stod etc.. like:

// std::string -> int
std::string str = "1000000";
int i = to_numeric<int>(str);

// std::string -> long
std::string str = "100000000000";
long i = to_numeric<long>(str);

// std::string -> float
std::string str = "10000.1";
float i = to_numeric<float>(str);

But I do not know how to make the partial specialization:

template<class T>
int to_numeric(const std::string &str, size_t *pos = 0, int base = 10) {
    return std::stol(str, pos, base);
};

template<>
long to_numeric<long>(const std::string &str, size_t *pos, base) {
    return std::stol(str, pos, base);
};

template<>
float to_numeric<float>(const std::string &str, size_t *pos) {
    return std::stof(str, pos);
};
// .....

Errors:

to_numeric.cpp:76:79: error: default argument specified in explicit specialization [-fpermissive]
to_numeric.cpp:76:12: error: template-id 'to_numeric<float>' for 'float to_numeric(const string&, size_t*)' does not match any template declaration
make: *** [build] Error 1
like image 280
Robbin Avatar asked Nov 04 '12 18:11

Robbin


People also ask

What does the stoi function do in C++?

What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.

What library is stoi in C++?

std::stoi is a standard library function, not a keyword. A keyword is something like for or new .

What is Stoll C++?

std::stoll(): This function converts a string, provided as an argument in the function call, to long long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long long int.


1 Answers

You specify a primary template which takes three arguments (str, pos, and base) but you try to specialize it with function templates taking just one argument. Clearly, this doesn't work: The specializations need to match the primary template.

Partial specializations of function templates are not [yet?] supported. If you need a partially specialized function template you need to do the partial specialization indirectly: You'd delegate to a class template and partially specialized that. The class template may have just one static function. Of course, in your example you don't use partial specialization but full specialization.

like image 52
Dietmar Kühl Avatar answered Oct 13 '22 23:10

Dietmar Kühl