接受字符*的模板化函数

Templated function accepting char*

本文关键字:函数 字符      更新时间:2023-10-16

我有一个模板化函数,我不知道如何编写类型 *unsigned const char** ?! 的规范

我为简单的类型(int,long ...(做了如下:

template <typename T>
void ConvertTypeToString(const T p_cszValue, std::string& p_szValue)
{
    p_szValue = p_cszValue;     
}
//Template Specialization for int
template <>
void ConvertTypeToString<int>(const int p_iValue, std::string& p_szValue)
{           
    GetFormattedString(p_iValue,p_szValue);
}
//Template Specialization for double
template <>
void ConvertTypeToString<double>(const double p_dValue, std::string& p_szValue)
{               
    GetFormattedString(p_dValue,p_szValue);     
}
在这里,我

卡住了,我无法弄清楚我应该写什么? 下面的代码无法编译。

//for unsigned char* const   
template <>
void ConvertTypeToString<unsigned char*>(const unsigned char* p_ucValue, std::string& p_szValue)
{   
    p_szValue.push_back(p_ucValue);
}

那么要编写的正确代码是什么,以考虑 usigned char* 常量

比克你

您将const放在错误的位置,它应该是:

template <>
void ConvertTypeToString<unsigned char*>(unsigned char* const p_ucValue, std::string& p_szValue)
{   
    p_szValue.push_back(p_ucValue);
}

通常最好添加重载而不是模板专用化。这允许您传递任何参数,包括指向 const 的指针:

void ConvertTypeToString(const unsigned char* const p_ucValue, std::string& p_szValue) { p_szValue.push_back(p_ucValue); }