Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates and constant strings

Tags:

c++

templates

I've got a function I'm wanting to template, at the moment I have two different versions for std::string and std::wstring.

The function (stripped down) is 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 an issue getting the constant strings 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 which takes a char* array. Normally to fix this I'd declare the constant string as const T tofind = L"\"' ", but then it wouldn't work with std::string.

I don't have much experience with templates and so I don't really know how to fix this issue.

like image 309
user1520427 Avatar asked Dec 04 '12 07:12

user1520427


1 Answers

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

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"\"' ");
}
like image 128
Karthik T Avatar answered Oct 21 '22 15:10

Karthik T