C++模板:如何根据数据类型有条件地编译不同的代码?

Geo*_* T. 4 c++ templates

这是一个小例子,说明了我的问题的本质:

#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()根据我正在使用的对象的类型进行编译.

谢谢

zet*_*t42 6

使用std::char_traits<CharT>.

您可以替换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的,因此没有必要将返回类型限制为常量引用.


Aja*_*jay 6

如果您使用的是 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)

不会为给定的模板实例编译未满足条件的分支。