c++ - 模板和常量字符串

标签 c++ templates

我有一个我想要模板化的函数,目前我有两个不同版本的 std::stringstd::wstring

函数(精简)是这样的

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

Tstd::stringstd::wstring_Tc charwchar_t。我在获取我定义的常量字符串以在模板版本中工作时遇到问题。上面的代码适用于 std::string 但不适用于 std::wstring 因为 std::wstring 没有构造函数,它需要一个char* 数组。通常要解决此问题,我会将常量字符串声明为 const T tofind = L"\"' ",但它不适用于 std::string

我对模板没有太多经验,所以我真的不知道如何解决这个问题。

最佳答案

您可以将 const 创建移动到它自己的工厂函数中,并将该函数分别专门用于 stringwstring

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"\"' ");
}

关于c++ - 模板和常量字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13697898/

相关文章:

c++ - c++中的背景音乐

c++ - 程序(三角旋转)异常终止

C++将 friend 添加到模板类以进行类型转换

C++11 非模板化基类中的纯虚拟 'templated' 返回类型

c++ - 如何使用 g++ 编译 openmp

c++ - C 和 C++ 中奇怪的类似函数的语法

c++ - 使用 extern "C"在 C++ 程序中包含 header 时出错

c++ - 使用类模板需要模板参数

c++ - 在使用模板模板参数时出现荒谬的错误

c++ - 将函数放入模板