Following C++ Most efficient way to compare a variable to multiple values?, I am trying to build a template function with an initializer_list
as an argument. The problem arises when I use strings only. I have the following code :
functions.hpp
template <typename T>
bool is_in(T const& val, initializer_list<T> const& liste)
{
for (const auto& i : liste)
if (val == i) return true;
return false;
};
main.cpp
#include "functions.hpp"
using namespace std;
int main()
{
string test("hello");
if (is_in(test, {"foo", "bar"}))
cout << "good" << endl;
else
cout << "bad" << endl;
return 0;
}
and I get the following error :
main.cpp: In function ‘int main()’:
main.cpp:18:34: error: no matching function for call to ‘is_in(std::string&, <brace-enclosed initializer list>)’
main.cpp:18:34: note: candidate is:
In file included from personnage.hpp:11:0,
from main.cpp:1:
functions.hpp:16:6: note: template<class T> bool is_in(const T&, const std::initializer_list<_Tp>&)
functions.hpp:16:6: note: template argument deduction/substitution failed:
main.cpp:18:34: note: deduced conflicting types for parameter ‘_Tp’ (‘std::basic_string<char>’ and ‘const char*’)
The thing I don't understand is : when instead of string
I use int
or double
in my main
, everything goes perfectly well... A quick and dirty fix was to declare is_in
as a function of strings only, but it is not very satisfactory.
Does anyone know how to keep the template and use string all the same?