[英]Templates and constant strings
I've got a function I'm wanting to template, at the moment I have two different versions for std::string
and std::wstring
. 我有一个我想要模板的函数,目前我有两个不同版本的std::string
和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
. T
是std::string
或std::wstring
, _Tc
是char
或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. 上面的代码适用于std::string
但不适用于std::wstring
因为没有std::wstring
构造函数,它接受一个char*
数组。 Normally to fix this I'd declare the constant string as const T tofind = L"\\"' "
, but then it wouldn't work with std::string
. 通常为了解决这个问题,我将常量字符串声明为const T tofind = L"\\"' "
,但是它不能用于std::string
。
I don't have much experience with templates and so I don't really know how to fix this issue. 我对模板没有太多经验,所以我真的不知道如何解决这个问题。
You can move the const creation into its own factory function and specialize the function for string
and wstring
seperately. 您可以将const创建移动到其自己的工厂函数中,并单独专门设置string
和wstring
的函数。
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"\"' ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.