I'm writing function working with STL containers that have iterator.
And I'm trying to handle container that doesn't.
my template function:
template <typename T>
void easyfind(...)
{
throw std::invalid_argument("No iterator");
}
template <typename T>
typename T::iterator easyfind(T& cont, int tofind)
{
typename T::iterator iter;
iter = std::find(cont.begin(), cont.end(), tofind);
if (iter == cont.end())
throw std::out_of_range("Cannot find");
return iter;
}
main.cpp:
// @ list
{
std::list<int> L;
std::list<int>::iterator iter;
L.push_back(5);
L.push_back(6);
L.push_back(7);
try
{
iter = easyfind(L, 7);
std::cout << "found " << *iter << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
// @ stack ( no iterator )
{
std::stack<int> S;
S.push(10);
S.push(11);
S.push(12);
try
{
easyfind(S, 12); // expect fallback case
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
I thought easyfind with stack would call void easyfind(...)
, but:
main.cpp:88:4: error: no matching function for call to 'easyfind'
easyfind(S, 12);
^~~~~~~~
./easyfind.hpp:21:6: note: candidate template ignored: couldn't infer template argument 'T'
void easyfind(...);
^
./easyfind.hpp:27:22: note: candidate template ignored: substitution failure [with T = std::stack<int>]: no type named 'iterator' in 'std::stack<int>'
typename T::iterator easyfind(T& cont, int tofind);
The second ignore is what I expected, but i don't understand why it cannot call fallback function. What am I missing?