模板函数接受char *

时间:2018-03-13 10:20:41

标签: c++ templates

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

我为简单类型(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 是什么?

比你

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

通常首选添加重载而不是模板特化。这允许您传递任何参数,包括指向const:

的指针
void ConvertTypeToString(const unsigned char* const p_ucValue, std::string& p_szValue) { p_szValue.push_back(p_ucValue); }
相关问题