Patterns and constant strings

I have a function that I want to create in a template, at the moment I have two different versions for std::string and std::wstring .

The function (truncated) looks like this:

 template <class T, class _Tc> std::vector<T> TokenizeArgs(const T& in) { const T tofind = T("\"' "); .. do stuff .. } 

T is either std::string or std::wstring , and _Tc is either char or wchar_t . I'm having a problem getting constant strings that I define to work in the template version. The above code works for std::string , but not for std::wstring , because there is no constructor for std::wstring that accepts a char* array. Normally, to fix this, I would declare a constant string as const T tofind = L"\"' " , but then it would not work with std::string .

I don’t have much experience with templates, so I really don’t know how to fix this problem.

+6
source share
1 answer

You can move the const creation into your own factory function and specialize the function for string and wstring separately.

 const T tofind = CreateConst<T>(); template <class T> const T CreateConst(); template <> const std::string CreateConst<std::string>() { return std::string("\"' "); } template <> const std::wstring CreateConst<std::wstring>() { return std::wstring(L"\"' "); } 
+6
source

All Articles