1

If I have code such as:

std::wstring s(L"...");
bool allCharsEqual = 
        std::find_if(s.begin(), 
                     s.end(), 
                     std::bind1st(std::not_equal_to<std::wstring::value_type>(),
                                  mystring[0]))  // ^^^^^^^^^^^^^^^^^^^^^^^^
        == s.end();

I would like to have a generic expression in the marked location which would also work if I changed the variable type to std::string. Is this possible?

I realize I could put this in an extra function and template it with the string type, but is there another way?

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131

2 Answers2

4

You can use decltype in C++11:

std::not_equal_to<decltype(s)::value_type>()

Or in C++14 you can use transparent comparators and just skip the template argument entirely:

std::not_equal_to<>()

If you're stuck with C++03, you could make a typedef so that you only have a single place you need to update to change types. This is good practice in general if you can't use auto and have types which you forsee changing.

typedef std::wstring str_t
Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
2

I think decltype is what your are looking for.

Since decltype is only available in C++11, maybe making your code a template would help if you have to code pre-11

template <typename STRING_TYPE> 
bool allCharsEqual(STRING_TYPE s){
    /* ... */
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185