How to write template code that handles type conversion for strings?

I tried to create a simple function that allowed me to check if there was a line in this list. Here is a 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'm trying to check if std :: wstring is in the const list wchar_t * consts.

This compiles using the MS compiler (and seems to work), but GCC complains that no types can be obtained to make it work. Interestingly, it also no longer compiles with the MS compiler if I switch the order of the template parameters so that the 6th line reads:

template<typename T, typename T2>

In this case, the compiler says that T is ambiguous.

I tried several options, such as using only one template parameter, but then I can no longer call it with strings and pointers.

- - ?

+4
2

GCC 4.8.1 :

#include <algorithm>

std::find <algorithm>. ++, MSVC, . , <set> <initializer_list>.

.

+2

find ( - ),

#include <algorithm>

gcc 4.9.0

+1

All Articles