I was trying to make a simple function that allowed checking if a string was in a given list. Here is some demo code:
#include <string>
#include <iostream>
#include <set>
#include <initializer_list>
template<typename T2, typename T>
bool contains(T const& value, std::initializer_list<T2> const& set)
{
return std::find(std::begin(set), std::end(set), value) != std::end(set);
}
int main(void)
{
std::set<std::wstring> values = { L"bar", L"not" };
for (std::wstring val : values) {
std::wcout << "\"" << val << "\" ";
if (contains(val, { L"foo", L"bar", L"baz", L"doom" })) {
std::wcout << "found" << std::endl;
}
else {
std::wcout << "not found" << std::endl;
}
}
}
As you can see I am trying to check if a std::wstring is in a list of const wchar_t*consts.
This compiles with the MS compiler (and seems to work) but GCC complains that no types to make it work can be derived. Interestingly it also doesn't compile with the MS compiler anymore if I switch the order of the template parameters so the 6th line reads:
template<typename T, typename T2>
In that case the compiler says T is ambiguous.
I've tried a few variations like using only one template parameter but then I can't call it with strings and pointers anymore.
How do I do this - if possible - properly?