Reputation: 1149
I am trying to learn variadic template. I was looking an youtube video where the host had some example. I tried to copy the example and tried compiling but I get error saying "no matching function for call to to_string
"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
template <class T>
std::string to_string_impl(const T &val) {
std::stringstream ss;
ss << val;
return ss.str();
}
template <class t>
std::vector<std::string> to_string() {
return {};
}
template <typename P1, typename... Param>
std::vector<std::string> to_string(const P1 &p1, const Param &... param) {
std::vector<std::string> ret;
ret.push_back(to_string_impl(p1));
const auto remainder = to_string(param...); // <----- compiler error coming from this line
ret.insert(ret.begin(), remainder.begin(), remainder.end());
return ret;
}
int main() {
std::vector<std::string> vec = to_string("Hello", 9.0);
for (auto v : vec) {
std::cout << v << std::endl;
}
}
Upvotes: 1
Views: 182
Reputation: 7324
The error is
...
prog.cpp:23:35: error: no matching function for call to ‘to_string()’
const auto remainder = to_string(param...);
~~~~~~~~~^~~~~~~~~~
prog.cpp:14:26: note: candidate: template<class t> std::vector<std::__cxx11::basic_string<char> > to_string()
std::vector<std::string> to_string() {
^~~~~~~~~
prog.cpp:14:26: note: template argument deduction/substitution failed:
prog.cpp:23:35: note: couldn't deduce template parameter ‘t’
const auto remainder = to_string(param...);
~~~~~~~~~^~~~~~~~~~
...
You've defined your base case function as
template <class t>
std::vector<std::string> to_string() {
return {};
}
And the error is that the template parameter t
can't be deduced, because it isn't used as a parameter and you aren't explicitly specifying it (e.g. to_string<int>()
, which you can't do here anyway). Just get rid of it.
std::vector<std::string> to_string() {
return {};
}
Upvotes: 1