这是一个小例子,说明了我的问题的本质:
#include <iostream>
using namespace std ;
typedef char achar_t ;
template < class T > class STRING
{
public:
T * memory ;
int size ;
int capacity ;
public:
STRING() {
size = 0 ;
capacity = 128 ;
memory = ( T *) malloc( capacity * sizeof(T) ) ;
}
const STRING& operator=( T * buf) {
if ( typeid(T) == typeid(char) )
strcpy( memory, buf ) ;
else
wcscpy( memory, buf ) ;
return *this ;
}
} ;
void main()
{
STRING<achar_t> a ;
STRING<wchar_t> w ;
a = "a_test" ;
w = L"w_test" ;
cout << " a = " << a.memory << endl ;
cout << " w = " << w.memory << endl ;
}
有人可以帮我编译以上吗?这是基于我正在使用的对象的类型与strcpy((或wcscpy((编译的。
谢谢
使用std::char_traits<CharT>
。
您可以通过组合静态方法std::char_traits::length()
和std::char_traits::copy()
来替换strcpy()
和wcscpy()
。这也将使您的代码更加通用,因为std::char_traits
具有char16_t
和char32_t
的专业。
STRING& operator=( T const * buf) {
// TODO: Make sure that buffer size for 'memory' is large enough.
// You propably also want to assign the 'size' member.
auto len = std::char_traits< T >::length( buf );
std::char_traits< T >::copy( memory, buf, len );
return *this ;
}
旁注:
- 我将参数
buf
的类型更改为T const*
,因为将字符串字面的字符串分配给指向非CONST数据的指针是不合法的。我们只需要阅读访问buf
指向的数据。 - 我将返回类型更改为
STRING&
,因为这是分配运算符通常声明的方式。该方法必须是非const的,因此将返回类型限制为常数参考没有意义。
如果您使用的是C 17,则可以使用if constexpr
:
if constexpr (std::is_same<char, T>::value)
strcpy( memory, buf );
else
wcscpy( memory, buf );
失败条件的分支将不会为给定的模板实例化编译。
您可以使用模板专业化。
template<typename T>
class STRING {
public:
T * memory ;
int size ;
int capacity ;
public:
STRING() {
size = 0 ;
capacity = 128 ;
memory = ( T *) malloc( capacity * sizeof(T) ) ;
}
STRING const & operator=(T * buf);
};
,您为想要的类型定义了
类型的专业化template<> STRING<achar_t> const & STRING<achar_t>::operator=(achar_t * buf)
{
strcpy(memory, buf );
return *this;
}
template<> STRING<wchar_t> const & STRING<wchar_t>::operator=(wchar_t * buf)
{
wcscpy( memory, buf );
return *this;
}
我没有测试此代码,但是您可以在此处找到更多信息http://en.cppreference.com/w/cpp/language/template_specialization