C ++ templates: how to conditionally compile other code based on data type?

Here is a small example illustrating the essence of my question:

#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 ;
}

Can someone help me compile the above? This somehow compiles either using strcpy () or wcscpy () based on the type of object I am using.

Thank you

+4
source share
3 answers

Use std::char_traits<CharT>.

You can replace strcpy()and wcscpy()by combining static methods std::char_traits::length()and std::char_traits::copy(). It will also make your code more general because it std::char_traitshas specializations for char16_tand 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 ;
 }

Side notes:

  • buf T const*, , . , buf.
  • STRING&,
+6

++ 17, if constexpr:

if constexpr (std::is_same<char, T>::value)
   strcpy( memory, buf );
else
   wcscpy( memory, buf );

, , .

+2

.

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;
}

I have not tested this code, but here you can find more information http://en.cppreference.com/w/cpp/language/template_specialization

0
source

Source: https://habr.com/ru/post/1678563/


All Articles