这是一个小例子,说明了我的问题的本质:
#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 ;
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我编译一下吗?这是以某种方式使用strcpy()或wcscpy()根据我正在使用的对象的类型进行编译.
谢谢
您可以替换strcpy()并wcscpy()组合静态方法std::char_traits::length()和std::char_traits::copy().这也将使您的代码更通用,因为它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 ;
}
Run Code Online (Sandbox Code Playgroud)
附注:
buf,T const*因为将字符串文字指定给指向非常量数据的指针是不合法的.我们只需要读取访问指向的数据buf.STRING&因为这通常是声明赋值运算符的方式.该方法必须是非const的,因此没有必要将返回类型限制为常量引用.如果您使用的是 C++17,您也可以使用if constexpr:
if constexpr (std::is_same<char, T>::value)
strcpy( memory, buf );
else
wcscpy( memory, buf );
Run Code Online (Sandbox Code Playgroud)
不会为给定的模板实例编译未满足条件的分支。
| 归档时间: |
|
| 查看次数: |
606 次 |
| 最近记录: |