Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/4: Рейтинг темы: голосов - 4, средняя оценка - 5.00
18 / 18 / 1
Регистрация: 27.01.2010
Сообщений: 150

string, template, char_tr

19.02.2012, 20:35. Показов 820. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
есть строки, на шаблонах, преподаватель прикапался к индексированию, нужен мистический класс, который появляется при взятии индекса и контролирует изменение того, куда сохранили ссылку на элемент, если потом элемент меняют, то должны строки с общим буфером разделиться и образовать новую с измененным.
мой код без этой ...:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <exception>
#include <string.h>
//#include <iostream>
 
//using namespace std;
 
 
#ifdef NDEBUG
#   pragma comment(lib, "lib-Release.lib")
#else
#   pragma comment(lib, "lib-Debug.lib")
#   define _CRTDBG_MAP_ALLOC
#   include <crtdbg.h>
void debug_initMemLeaksCheck();
#endif
 
#define TMP template <typename T> 
#define STR string<T>::
#include <wchar.h>
 
#if !defined(NDEBUG)
void debug_initMemLeaksCheck()
{
    int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
    _CrtSetDbgFlag(tmpDbgFlag);
}
 
#endif
 
 
template <class T> class buffer;
 
template <class T> class string
{
public:
    //friend buffer<T>;
    //длина 
    unsigned int length() const;
 
    //печать
    void print() const;
    //преобразование в классическую строку
    const T * c_str() const;
    operator const T*() const;
 
 
 
    //конструкторы
    string(const T *a);
    string(int n = 0);
    string(const string &a);
    explicit string(const T a);
    //деструкторы
    virtual ~string();
 
    
    //присваивание
    void operator=(const string &a);
    void operator=(const T *a);
    void operator=(const T a);
 
    void assign(const string &a);
    void assign(const T *a);
    void assign(const T a);
    //сложения и тд
    string operator+(const string &a);
    static string concat(const string &a, const string &b);
 
    void operator+=(const T *a);
    void operator+=(const T a);
    void operator+=(const string &a); 
 
    //сравнения
    bool operator==(const string &a) const;
    bool operator!=(const string &a) const;
    bool operator<=(const string &a) const;
    bool operator>=(const string &a) const;
    bool operator<(const string &a) const;
    bool operator>(const string &a) const;
    
    bool operator==(const T * a) const;
    bool operator!=(const T * a) const;
    bool operator<=(const T * a) const;
    bool operator>=(const T * a) const;
    bool operator<(const T * a) const;
    bool operator>(const T * a) const;
    
    bool operator==(const T  a) const;
    bool operator!=(const T  a) const;
    bool operator<=(const T  a) const;
    bool operator>=(const T  a) const;
    bool operator<(const T  a) const;
    bool operator>(const T  a) const;
 
    static int my_cmp(const T * a, const string  & b);
    static int my_cmp(const T  a, const string  & b);
    static int my_cmp(const buffer<T> * a, const buffer<T> * b);
    static int my_cmp(const buffer<T> * a, const T  * b);
    static int my_cmp(const buffer<T> * a, const T b);
    //работа с памятью
    static void *my_malloc(size_t size);
    static void * my_realloc(void *str, size_t size);
    static void my_free(string *a);
    //работа с индексированием
    //T & operator [](int index);
    T operator[](int i) const;
    //class XZ
    //{
    //  XZ (string &st, unsigned int ind)
    //  {
    //      str = st, index  = index;
    //      
    //  }
    //  operator T()
    //  {
    //      T c = str.buf->str[index];
    //      return c;
    //  }
    //  XZ* operator =(T c) 
    //  {
    //      str[index] = c;
    //      //this->str.set_by_index(this->index, c); 
    //      return this; 
    //  }
    //private:
    //  string & str;
    //  unsigned int index;
 
 
    //};
    //XZ operator[](unsigned int ind)
    //{
    //  XZ(*this, ind);
    //}
 
 
 
    
protected:
    buffer<T> * buf;
};
 
template <class T> class buffer
{
public:
    friend string<T>;
private:
    buffer(unsigned int size)
    {
        str = (T *)string<T>::my_malloc(size);//КАК????????
        numb_copies = 1;
        leng = size;
    }
    virtual ~buffer()
    {
            free(str);
    }
    T * str;
    unsigned int leng;
    unsigned int numb_copies;
};
 
 
 
TMP bool __fastcall operator==(const T * a, const string<T> &b);
TMP bool __fastcall operator!=(const T * a, const string<T> &b);
TMP bool __fastcall operator<=(const T * a, const string<T> &b);
TMP bool __fastcall operator>=(const T * a, const string<T> &b);
TMP bool __fastcall operator< (const T * a, const string<T> &b);
TMP bool __fastcall operator> (const T * a, const string<T> &b);
 
TMP bool __fastcall operator==(const T  a, const string<T> &b);
TMP bool __fastcall operator!=(const T  a, const string<T> &b);
TMP bool __fastcall operator<=(const T  a, const string<T> &b);
TMP bool __fastcall operator>=(const T  a, const string<T> &b);
TMP bool __fastcall operator< (const T  a, const string<T> &b);
TMP bool __fastcall operator> (const T  a, const string<T> &b);
 
 
 
 
 
//TMP T & STR operator [](int index)
//{
//  if (buf->numb_copies == 1)
//      return buf->str[index];
//  else
//  {
//      buffer<T> * temp = new buffer<T>(buf->leng);
//      buf->numb_copies --;
//      memcpy(temp->str, buf->str, sizeof(T) * buf->leng);
//      buf = temp;
//      return buf->str[index];
//
//  }
//
//}
 
//длина и n символ
TMP unsigned int STR length() const
{
    return buf->leng;
}
//TMP T STR operator[](int i)const
//{
//  return buf->str[i];
//}
//печать
TMP void STR print() const
{
    printf("%s\n", this->buf->str);
}
 
 
template <> void  string<wchar_t>::print() const
{
    printf("%ls\n", this->buf->str);
}
//преобразование в классическую строку
TMP const T * STR c_str() const
{
    return this->buf->str;
}
 
TMP STR operator const T*() const
{
    return this->buf->str;
}
 
//TODO SPIKE
int strlen(const wchar_t * str)
{
    return wcslen(str);
}
 
 
//конструкторы
TMP STR string(const T *a)
{
    unsigned int l = 1;
    buffer<T> *temp = new buffer<T>(l = strlen(a));
    buf = temp;
    memcpy(buf->str, a, l *sizeof(T));
}
TMP STR string(int n)
{
    buffer<T> *temp = new buffer<T>(n);
    temp->leng = 0;
    buf = temp;
}
TMP STR string(const string &a)
{
    (buf = a.buf)->numb_copies ++;
}
TMP STR string(const T a)
{
    buffer<T> *temp = new buffer<T>(1);
    buf = temp;
    buf->str[0] = a;
}
//деструкторы
TMP STR ~string()
{
    if ( --(buf->numb_copies) == 0)
        delete buf;
}
 
 
//присваивание
TMP void STR operator=(const string<T> &a)
{
    if (a.buf != buf)
    {
        my_free(this);
        (buf = a.buf)->numb_copies ++;
    }
}
TMP void STR operator=(const T *a)
{
    unsigned int l = strlen(a);
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, l );
        buf->leng = l;
 
    }
    else
    {
        
        --(buf->numb_copies);
        buf = new buffer<T>(l);
    }
    memcpy(buf->str, a, l * sizeof(T));
 
}
TMP void STR operator=(const T a)//так то шаблонами тут пройтись
{
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, 1);
        buf->leng = 1;
 
    }
    else
    {
        --(buf->numb_copies);
        buf = new buffer<T>(1);
    }
    buf->str[1] = 0;
    buf->str[0] = a;
}
 
TMP void STR assign(const string<T> &a)
{
    (*this) = a;
}
TMP void STR assign(const T *a)
{
    (*this) = a;
}
TMP void STR assign(const T a)
{
    (*this) = a;
}
//сложения и тд
TMP string<T> STR operator+(const string<T> &a)
{
    buffer<T> * temp = new buffer<T>(a.buf->leng + buf->leng);
    memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, a.buf->leng * sizeof(T));
    string t;
    my_free(&t);//как-то не очень
    t.buf = temp;
    return t;
}
TMP string<T> STR concat(const string<T> &a, const string<T> &b)
{
    return (string<T>)a+ b;
}
 
TMP void STR operator+=(const T *a)
{
    unsigned int l = strlen(a);
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + l);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a, l * sizeof(T));
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + l);
        memcpy(&buf->str[buf->leng], a, l * sizeof(T));
        buf->leng += l;
    }
}
TMP void STR operator+=(const T a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + 1);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng * sizeof(T)), temp->str[buf->leng] = a;
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + 1);
        buf->str[buf->leng] = a;
        buf->leng += 1;
    }
}
TMP void STR operator+=(const string<T> &a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + a.buf->leng);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + a.buf->leng);
        memcpy(&buf->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf->leng += a.buf->leng;
    }
}
 
//сравнения
#define comp(op) TMP bool STR operator op(const string<T> &a)const\
{\
    return  my_cmp(buf, a.buf) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T *a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T * a, const string<T>&b)\
{\
    return   STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T  a, const string<T>&b)\
{\
    return  STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
TMP int STR my_cmp(const buffer<T> * a, const buffer<T> * b)
{
    return 0;
}
TMP int STR my_cmp(const buffer<T> * a, const T  * b)
{
    return 0;
}
TMP int STR my_cmp(const T * a, const string<T>  & b)
{
    return 0;
}
//вставка для wchar_t
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const buffer<wchar_t> * b)
{
    return wcscmp(a->str, b->str);
}
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const wchar_t  * b)
{
    return wcscmp(a->str, b);
}
template <>int string<wchar_t>:: my_cmp(const wchar_t * a, const string<wchar_t>  & b)
{
    return wcscmp(a, b.buf->str);
}
 
//SPIKE for char
template <>int string<char>:: my_cmp(const buffer<char> * a, const buffer<char> * b)
{
    return strcmp(a->str, b->str);
}
template <>int string<char>:: my_cmp(const buffer<char> * a, const char  * b)
{
    return strcmp(a->str, b);
}
template <>int string<char>:: my_cmp(const char * a, const string<char>  & b)
{
    return strcmp(a, b.buf->str);
}
 
TMP int STR my_cmp(const T  a, const string<T>  & b)
{
    return a - b.buf->str[0];
}
TMP int STR my_cmp(const buffer<T> * a, const T b)
{
    return a->str[0] - b;
}
 
TMP void *STR my_malloc(size_t size)
{
    void * temp = malloc((size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else
    {
        ((T *)temp)[size] = 0;
        ((T *)temp)[0] = 0;
    }
    return temp;
}
TMP void * STR my_realloc(void *str, size_t size)
{
    void * temp = realloc(str, (size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else 
        ((T *)temp)[size] = 0;
    return temp;
}
TMP void STR my_free(string<T> *a)
{
    if (--(a->buf->numb_copies)  == 0)
        delete (a->buf);
}
 
template class string <char>;
template class buffer<char>;
template class string <wchar_t>;
template class buffer <wchar_t>;
примерный вариант нового класса:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    class CharTrait
    {
    public:
        CharTrait(MyString & string, unsigned int index);       
        CharTrait(const CharTrait & c);     
        operator T();       
        CharTrait* operator =(T c) {this->str.set_by_index(this->index, c); return this; }
        
    private:
        MyString & str;
        unsigned int index;
    };
 
    T operator[](unsigned int index) const {return this->_buf->_buffer[index];}
    CharTrait operator[](unsigned int index){return CharTrait(*this, index);}
    MyString & operator +=(T c);
    void set_by_index(int index, T c);
 
 
    template <class T> MyString<T>::CharTrait::CharTrait(MyString<T> & string, unsigned int index):str(string)
    {
        this->index = index;
    }
 
    template <class T> MyString<T>::CharTrait::CharTrait(const CharTrait & c):str(c.str)
    {
        this->index = c.index;
    }
 
    template <class T> MyString<T>::CharTrait::operator T()
    {
        T c = this->str._buf->_buffer[this->index];
        return c;
    }
где подобная штука описана и как написать? сам погряз в зависимостях и шаблонах.

Добавлено через 9 минут
пытаюсь добавить класс с конструктором, получаю
error C2758: 'string<T>::XZ::str2' : must be initialized in constructor base/member initializer list
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <exception>
#include <string.h>
//#include <iostream>
 
//using namespace std;
 
 
#ifdef NDEBUG
#   pragma comment(lib, "lib-Release.lib")
#else
#   pragma comment(lib, "lib-Debug.lib")
#   define _CRTDBG_MAP_ALLOC
#   include <crtdbg.h>
void debug_initMemLeaksCheck();
#endif
 
#define TMP template <typename T> 
#define STR string<T>::
#include <wchar.h>
 
#if !defined(NDEBUG)
void debug_initMemLeaksCheck()
{
    int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
    _CrtSetDbgFlag(tmpDbgFlag);
}
 
#endif
 
 
template <class T> class buffer;
 
template <class T> class string
{
public:
    //friend buffer<T>;
    //длина 
    unsigned int length() const;
 
    //печать
    void print() const;
    //преобразование в классическую строку
    const T * c_str() const;
    operator const T*() const;
 
 
 
    //конструкторы
    string(const T *a);
    string(int n = 0);
    string(const string &a);
    explicit string(const T a);
    //деструкторы
    virtual ~string();
 
    
    //присваивание
    void operator=(const string &a);
    void operator=(const T *a);
    void operator=(const T a);
 
    void assign(const string &a);
    void assign(const T *a);
    void assign(const T a);
    //сложения и тд
    string operator+(const string &a);
    static string concat(const string &a, const string &b);
 
    void operator+=(const T *a);
    void operator+=(const T a);
    void operator+=(const string &a); 
 
    //сравнения
    bool operator==(const string &a) const;
    bool operator!=(const string &a) const;
    bool operator<=(const string &a) const;
    bool operator>=(const string &a) const;
    bool operator<(const string &a) const;
    bool operator>(const string &a) const;
    
    bool operator==(const T * a) const;
    bool operator!=(const T * a) const;
    bool operator<=(const T * a) const;
    bool operator>=(const T * a) const;
    bool operator<(const T * a) const;
    bool operator>(const T * a) const;
    
    bool operator==(const T  a) const;
    bool operator!=(const T  a) const;
    bool operator<=(const T  a) const;
    bool operator>=(const T  a) const;
    bool operator<(const T  a) const;
    bool operator>(const T  a) const;
 
    static int my_cmp(const T * a, const string  & b);
    static int my_cmp(const T  a, const string  & b);
    static int my_cmp(const buffer<T> * a, const buffer<T> * b);
    static int my_cmp(const buffer<T> * a, const T  * b);
    static int my_cmp(const buffer<T> * a, const T b);
    //работа с памятью
    static void *my_malloc(size_t size);
    static void * my_realloc(void *str, size_t size);
    static void my_free(string *a);
    //работа с индексированием
    //T & operator [](int index);
    T operator[](int i) const;
    class XZ
    {
        XZ (string &st, unsigned int ind)
        {
            str2 = st, index  = index;
            
        }
        operator T()
        {
            T c = str.buf->str[index];
            return c;
        }
    //  XZ* operator =(T c) 
    //  {
    //      str[index] = c;
    //      //this->str.set_by_index(this->index, c); 
    //      return this; 
    //  }
    private:
        string & str2;
        unsigned int index;
 
 
    };
    //XZ operator[](unsigned int ind)
    //{
    //  XZ(*this, ind);
    //}
 
 
 
    
protected:
    buffer<T> * buf;
};
 
template <class T> class buffer
{
public:
    friend string<T>;
private:
    buffer(unsigned int size)
    {
        str = (T *)string<T>::my_malloc(size);//КАК????????
        numb_copies = 1;
        leng = size;
    }
    virtual ~buffer()
    {
            free(str);
    }
    T * str;
    unsigned int leng;
    unsigned int numb_copies;
};
 
 
 
TMP bool __fastcall operator==(const T * a, const string<T> &b);
TMP bool __fastcall operator!=(const T * a, const string<T> &b);
TMP bool __fastcall operator<=(const T * a, const string<T> &b);
TMP bool __fastcall operator>=(const T * a, const string<T> &b);
TMP bool __fastcall operator< (const T * a, const string<T> &b);
TMP bool __fastcall operator> (const T * a, const string<T> &b);
 
TMP bool __fastcall operator==(const T  a, const string<T> &b);
TMP bool __fastcall operator!=(const T  a, const string<T> &b);
TMP bool __fastcall operator<=(const T  a, const string<T> &b);
TMP bool __fastcall operator>=(const T  a, const string<T> &b);
TMP bool __fastcall operator< (const T  a, const string<T> &b);
TMP bool __fastcall operator> (const T  a, const string<T> &b);
 
 
 
 
 
//TMP T & STR operator [](int index)
//{
//  if (buf->numb_copies == 1)
//      return buf->str[index];
//  else
//  {
//      buffer<T> * temp = new buffer<T>(buf->leng);
//      buf->numb_copies --;
//      memcpy(temp->str, buf->str, sizeof(T) * buf->leng);
//      buf = temp;
//      return buf->str[index];
//
//  }
//
//}
 
//длина и n символ
TMP unsigned int STR length() const
{
    return buf->leng;
}
//TMP T STR operator[](int i)const
//{
//  return buf->str[i];
//}
//печать
TMP void STR print() const
{
    printf("%s\n", this->buf->str);
}
 
 
template <> void  string<wchar_t>::print() const
{
    printf("%ls\n", this->buf->str);
}
//преобразование в классическую строку
TMP const T * STR c_str() const
{
    return this->buf->str;
}
 
TMP STR operator const T*() const
{
    return this->buf->str;
}
 
//TODO SPIKE
int strlen(const wchar_t * str)
{
    return wcslen(str);
}
 
 
//конструкторы
TMP STR string(const T *a)
{
    unsigned int l = 1;
    buffer<T> *temp = new buffer<T>(l = strlen(a));
    buf = temp;
    memcpy(buf->str, a, l *sizeof(T));
}
TMP STR string(int n)
{
    buffer<T> *temp = new buffer<T>(n);
    temp->leng = 0;
    buf = temp;
}
TMP STR string(const string &a)
{
    (buf = a.buf)->numb_copies ++;
}
TMP STR string(const T a)
{
    buffer<T> *temp = new buffer<T>(1);
    buf = temp;
    buf->str[0] = a;
}
//деструкторы
TMP STR ~string()
{
    if ( --(buf->numb_copies) == 0)
        delete buf;
}
 
 
//присваивание
TMP void STR operator=(const string<T> &a)
{
    if (a.buf != buf)
    {
        my_free(this);
        (buf = a.buf)->numb_copies ++;
    }
}
TMP void STR operator=(const T *a)
{
    unsigned int l = strlen(a);
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, l );
        buf->leng = l;
 
    }
    else
    {
        
        --(buf->numb_copies);
        buf = new buffer<T>(l);
    }
    memcpy(buf->str, a, l * sizeof(T));
 
}
TMP void STR operator=(const T a)//так то шаблонами тут пройтись
{
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, 1);
        buf->leng = 1;
 
    }
    else
    {
        --(buf->numb_copies);
        buf = new buffer<T>(1);
    }
    buf->str[1] = 0;
    buf->str[0] = a;
}
 
TMP void STR assign(const string<T> &a)
{
    (*this) = a;
}
TMP void STR assign(const T *a)
{
    (*this) = a;
}
TMP void STR assign(const T a)
{
    (*this) = a;
}
//сложения и тд
TMP string<T> STR operator+(const string<T> &a)
{
    buffer<T> * temp = new buffer<T>(a.buf->leng + buf->leng);
    memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, a.buf->leng * sizeof(T));
    string t;
    my_free(&t);//как-то не очень
    t.buf = temp;
    return t;
}
TMP string<T> STR concat(const string<T> &a, const string<T> &b)
{
    return (string<T>)a+ b;
}
 
TMP void STR operator+=(const T *a)
{
    unsigned int l = strlen(a);
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + l);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a, l * sizeof(T));
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + l);
        memcpy(&buf->str[buf->leng], a, l * sizeof(T));
        buf->leng += l;
    }
}
TMP void STR operator+=(const T a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + 1);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng * sizeof(T)), temp->str[buf->leng] = a;
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + 1);
        buf->str[buf->leng] = a;
        buf->leng += 1;
    }
}
TMP void STR operator+=(const string<T> &a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + a.buf->leng);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + a.buf->leng);
        memcpy(&buf->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf->leng += a.buf->leng;
    }
}
 
//сравнения
#define comp(op) TMP bool STR operator op(const string<T> &a)const\
{\
    return  my_cmp(buf, a.buf) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T *a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T * a, const string<T>&b)\
{\
    return   STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T  a, const string<T>&b)\
{\
    return  STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
TMP int STR my_cmp(const buffer<T> * a, const buffer<T> * b)
{
    return 0;
}
TMP int STR my_cmp(const buffer<T> * a, const T  * b)
{
    return 0;
}
TMP int STR my_cmp(const T * a, const string<T>  & b)
{
    return 0;
}
//вставка для wchar_t
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const buffer<wchar_t> * b)
{
    return wcscmp(a->str, b->str);
}
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const wchar_t  * b)
{
    return wcscmp(a->str, b);
}
template <>int string<wchar_t>:: my_cmp(const wchar_t * a, const string<wchar_t>  & b)
{
    return wcscmp(a, b.buf->str);
}
 
//SPIKE for char
template <>int string<char>:: my_cmp(const buffer<char> * a, const buffer<char> * b)
{
    return strcmp(a->str, b->str);
}
template <>int string<char>:: my_cmp(const buffer<char> * a, const char  * b)
{
    return strcmp(a->str, b);
}
template <>int string<char>:: my_cmp(const char * a, const string<char>  & b)
{
    return strcmp(a, b.buf->str);
}
 
TMP int STR my_cmp(const T  a, const string<T>  & b)
{
    return a - b.buf->str[0];
}
TMP int STR my_cmp(const buffer<T> * a, const T b)
{
    return a->str[0] - b;
}
 
TMP void *STR my_malloc(size_t size)
{
    void * temp = malloc((size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else
    {
        ((T *)temp)[size] = 0;
        ((T *)temp)[0] = 0;
    }
    return temp;
}
TMP void * STR my_realloc(void *str, size_t size)
{
    void * temp = realloc(str, (size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else 
        ((T *)temp)[size] = 0;
    return temp;
}
TMP void STR my_free(string<T> *a)
{
    if (--(a->buf->numb_copies)  == 0)
        delete (a->buf);
}
 
template class string <char>;
template class buffer<char>;
template class string <wchar_t>;
template class buffer <wchar_t>;
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
19.02.2012, 20:35
Ответы с готовыми решениями:

String в template
Здравствуйте. В программе используются преимущественно объекты класса string. Требуется иметь возможность передавать значение стринга в...

Ошибки: 1) use of class template requires template argument list 2) 'T' : undeclared identifier
Решил подправить свой класс с использованием шаблонов, но столкнулся со следующим косяком. Если я прописываю тело функций внутри описания...

Template definition of non-template при использовании частичной спецификации шаблонов
Всем привет! Есть задача написать шаблон класса, принимающего в качестве параметров типа шаблон и некоторый тип. Собственно, вот код: ...

4
DU
1500 / 1146 / 165
Регистрация: 05.12.2011
Сообщений: 2,279
19.02.2012, 20:35
Можете попробовать посмотреть в этой книге:
Эффективное использование С++. 35 новых способов улучшить стиль программирования
More Effective C++. 35 New Ways to Improve Your Programs and Designs
Автор: Скотт Майерс
http://www.ozon.ru/context/detail/id/2623946/

Главы 29 и 30.

Там описан подход как это делается. Ваш код не смотрел. В чем ошибки - не знаю.
Перед продолжением своего решения постарайтесь в сети скачать и прочитать указанные главы. Там вроде как раз речь идет о строках с отложенным копированием.


пытаюсь добавить класс с конструктором, получаю
error C2758: 'string<T>::XZ::str2' : must be initialized in constructor base/member initializer list
str2 у вас имеет тип ссылки на строку. ссылки должны инициализироваться в списке инициализации конструктора, а не в теле конструктора.


C++
1
2
3
4
5
 XZ (string &st, unsigned int ind)
:str2(st), index(ind);
{
   // str2 = st, index  = index; // вот тут еще была ошибка и index = index
}
1
18 / 18 / 1
Регистрация: 27.01.2010
Сообщений: 150
19.02.2012, 20:44  [ТС]
Цитата Сообщение от DU Посмотреть сообщение
Можете попробовать посмотреть в этой книге:
Эффективное использование С++. 35 новых способов улучшить стиль программирования
More Effective C++. 35 New Ways to Improve Your Programs and Designs
Автор: Скотт Майерс
http://www.ozon.ru/context/detail/id/2623946/

Главы 29 и 30.

Там описан подход как это делается. Ваш код не смотрел. В чем ошибки - не знаю.
Перед продолжением своего решения постарайтесь в сети скачать и прочитать указанные главы. Там вроде как раз речь идет о строках с отложенным копированием.


пытаюсь добавить класс с конструктором, получаю
error C2758: 'string<T>::XZ::str2' : must be initialized in constructor base/member initializer list
str2 у вас имеет тип ссылки на строку. ссылки должны инициализироваться в списке инициализации конструктора, а не в теле конструктора.


C++
1
2
3
4
5
 XZ (string &st, unsigned int ind)
:str2(st), index(ind);
{
   // str2 = st, index  = index; // вот тут еще была ошибка и index = index
}
тело конструктора должно быть пустым?
0
DU
1500 / 1146 / 165
Регистрация: 05.12.2011
Сообщений: 2,279
19.02.2012, 20:45
получается что так.
0
18 / 18 / 1
Регистрация: 27.01.2010
Сообщений: 150
19.02.2012, 21:06  [ТС]
можно вас еще поотвлекать тупыми ошибками?)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <exception>
#include <string.h>
//#include <iostream>
 
//using namespace std;
 
 
#ifdef NDEBUG
#   pragma comment(lib, "lib-Release.lib")
#else
#   pragma comment(lib, "lib-Debug.lib")
#   define _CRTDBG_MAP_ALLOC
#   include <crtdbg.h>
void debug_initMemLeaksCheck();
#endif
 
#define TMP template <typename T> 
#define STR string<T>::
#include <wchar.h>
 
#if !defined(NDEBUG)
void debug_initMemLeaksCheck()
{
    int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
    _CrtSetDbgFlag(tmpDbgFlag);
}
 
#endif
 
 
template <class T> class buffer;
 
template <class T> class string
{
public:
    //friend buffer<T>;
    //длина 
    unsigned int length() const;
 
    //печать
    void print() const;
    //преобразование в классическую строку
    const T * c_str() const;
    operator const T*() const;
 
 
 
    //конструкторы
    string(const T *a);
    string(int n = 0);
    string(const string &a);
    explicit string(const T a);
    //деструкторы
    virtual ~string();
 
    
    //присваивание
    void operator=(const string &a);
    void operator=(const T *a);
    void operator=(const T a);
 
    void assign(const string &a);
    void assign(const T *a);
    void assign(const T a);
    //сложения и тд
    string operator+(const string &a);
    static string concat(const string &a, const string &b);
 
    void operator+=(const T *a);
    void operator+=(const T a);
    void operator+=(const string &a); 
 
    //сравнения
    bool operator==(const string &a) const;
    bool operator!=(const string &a) const;
    bool operator<=(const string &a) const;
    bool operator>=(const string &a) const;
    bool operator<(const string &a) const;
    bool operator>(const string &a) const;
    
    bool operator==(const T * a) const;
    bool operator!=(const T * a) const;
    bool operator<=(const T * a) const;
    bool operator>=(const T * a) const;
    bool operator<(const T * a) const;
    bool operator>(const T * a) const;
    
    bool operator==(const T  a) const;
    bool operator!=(const T  a) const;
    bool operator<=(const T  a) const;
    bool operator>=(const T  a) const;
    bool operator<(const T  a) const;
    bool operator>(const T  a) const;
 
    static int my_cmp(const T * a, const string  & b);
    static int my_cmp(const T  a, const string  & b);
    static int my_cmp(const buffer<T> * a, const buffer<T> * b);
    static int my_cmp(const buffer<T> * a, const T  * b);
    static int my_cmp(const buffer<T> * a, const T b);
    //работа с памятью
    static void *my_malloc(size_t size);
    static void * my_realloc(void *str, size_t size);
    static void my_free(string *a);
    //работа с индексированием
    //T & operator [](int index);
    T operator[](int i) const;
    class XZ
    {
        XZ (string str, unsigned int ind):str(str), index(ind)
        {
        ;   //str = 0, index  = index;
            
        }
        operator T()
        {
            T c = str.buf->str[index];
            return c;
        }
        XZ* operator =(T c) 
        {
            str[index] = c;
            //this->str.set_by_index(this->index, c); 
        return this; 
        }
    private:
        string & str;
        unsigned int index;
 
 
    };
[COLOR="Red"]   XZ operator[](unsigned int ind)
    {
        return XZ(*this, ind);
    }
[/COLOR]
 
 
    
protected:
    buffer<T> * buf;
};
 
template <class T> class buffer
{
public:
    friend string<T>;
private:
    buffer(unsigned int size)
    {
        str = (T *)string<T>::my_malloc(size);//КАК????????
        numb_copies = 1;
        leng = size;
    }
    virtual ~buffer()
    {
            free(str);
    }
    T * str;
    unsigned int leng;
    unsigned int numb_copies;
};
 
 
 
TMP bool __fastcall operator==(const T * a, const string<T> &b);
TMP bool __fastcall operator!=(const T * a, const string<T> &b);
TMP bool __fastcall operator<=(const T * a, const string<T> &b);
TMP bool __fastcall operator>=(const T * a, const string<T> &b);
TMP bool __fastcall operator< (const T * a, const string<T> &b);
TMP bool __fastcall operator> (const T * a, const string<T> &b);
 
TMP bool __fastcall operator==(const T  a, const string<T> &b);
TMP bool __fastcall operator!=(const T  a, const string<T> &b);
TMP bool __fastcall operator<=(const T  a, const string<T> &b);
TMP bool __fastcall operator>=(const T  a, const string<T> &b);
TMP bool __fastcall operator< (const T  a, const string<T> &b);
TMP bool __fastcall operator> (const T  a, const string<T> &b);
 
 
 
 
 
//TMP T & STR operator [](int index)
//{
//  if (buf->numb_copies == 1)
//      return buf->str[index];
//  else
//  {
//      buffer<T> * temp = new buffer<T>(buf->leng);
//      buf->numb_copies --;
//      memcpy(temp->str, buf->str, sizeof(T) * buf->leng);
//      buf = temp;
//      return buf->str[index];
//
//  }
//
//}
 
//длина и n символ
TMP unsigned int STR length() const
{
    return buf->leng;
}
//TMP T STR operator[](int i)const
//{
//  return buf->str[i];
//}
//печать
TMP void STR print() const
{
    printf("%s\n", this->buf->str);
}
 
 
template <> void  string<wchar_t>::print() const
{
    printf("%ls\n", this->buf->str);
}
//преобразование в классическую строку
TMP const T * STR c_str() const
{
    return this->buf->str;
}
 
TMP STR operator const T*() const
{
    return this->buf->str;
}
 
//TODO SPIKE
int strlen(const wchar_t * str)
{
    return wcslen(str);
}
 
 
//конструкторы
TMP STR string(const T *a)
{
    unsigned int l = 1;
    buffer<T> *temp = new buffer<T>(l = strlen(a));
    buf = temp;
    memcpy(buf->str, a, l *sizeof(T));
}
TMP STR string(int n)
{
    buffer<T> *temp = new buffer<T>(n);
    temp->leng = 0;
    buf = temp;
}
TMP STR string(const string &a)
{
    (buf = a.buf)->numb_copies ++;
}
TMP STR string(const T a)
{
    buffer<T> *temp = new buffer<T>(1);
    buf = temp;
    buf->str[0] = a;
}
//деструкторы
TMP STR ~string()
{
    if ( --(buf->numb_copies) == 0)
        delete buf;
}
 
 
//присваивание
TMP void STR operator=(const string<T> &a)
{
    if (a.buf != buf)
    {
        my_free(this);
        (buf = a.buf)->numb_copies ++;
    }
}
TMP void STR operator=(const T *a)
{
    unsigned int l = strlen(a);
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, l );
        buf->leng = l;
 
    }
    else
    {
        
        --(buf->numb_copies);
        buf = new buffer<T>(l);
    }
    memcpy(buf->str, a, l * sizeof(T));
 
}
TMP void STR operator=(const T a)//так то шаблонами тут пройтись
{
    if( 1 == buf->numb_copies )
    {
        buf->str = (T *)my_realloc(buf->str, 1);
        buf->leng = 1;
 
    }
    else
    {
        --(buf->numb_copies);
        buf = new buffer<T>(1);
    }
    buf->str[1] = 0;
    buf->str[0] = a;
}
 
TMP void STR assign(const string<T> &a)
{
    (*this) = a;
}
TMP void STR assign(const T *a)
{
    (*this) = a;
}
TMP void STR assign(const T a)
{
    (*this) = a;
}
//сложения и тд
TMP string<T> STR operator+(const string<T> &a)
{
    buffer<T> * temp = new buffer<T>(a.buf->leng + buf->leng);
    memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, a.buf->leng * sizeof(T));
    string t;
    my_free(&t);//как-то не очень
    t.buf = temp;
    return t;
}
TMP string<T> STR concat(const string<T> &a, const string<T> &b)
{
    return (string<T>)a+ b;
}
 
TMP void STR operator+=(const T *a)
{
    unsigned int l = strlen(a);
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + l);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a, l * sizeof(T));
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + l);
        memcpy(&buf->str[buf->leng], a, l * sizeof(T));
        buf->leng += l;
    }
}
TMP void STR operator+=(const T a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + 1);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng * sizeof(T)), temp->str[buf->leng] = a;
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + 1);
        buf->str[buf->leng] = a;
        buf->leng += 1;
    }
}
TMP void STR operator+=(const string<T> &a)
{
    if (buf->numb_copies > 1)
    {
        buffer<T> * temp = new buffer<T>(buf->leng + a.buf->leng);
        buf->numb_copies --;
        memcpy(temp->str, buf->str, buf->leng), memcpy(&temp->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf = temp;
    }
    else
    {
        buf->str = (T *) my_realloc(buf->str, buf->leng + a.buf->leng);
        memcpy(&buf->str[buf->leng], a.buf->str, sizeof(T) * a.buf->leng);
        buf->leng += a.buf->leng;
    }
}
 
//сравнения
#define comp(op) TMP bool STR operator op(const string<T> &a)const\
{\
    return  my_cmp(buf, a.buf) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T *a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool STR operator op(const T a)const\
{\
    return  my_cmp(buf, a) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T * a, const string<T>&b)\
{\
    return   STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
#define comp(op) TMP bool __fastcall operator op(const T  a, const string<T>&b)\
{\
    return  STR my_cmp(a, b) op 0;\
}
 
comp(==)
comp(!=)
comp(<)
comp(>)
comp(<=)
comp(>=)
 
#undef comp
 
TMP int STR my_cmp(const buffer<T> * a, const buffer<T> * b)
{
    return 0;
}
TMP int STR my_cmp(const buffer<T> * a, const T  * b)
{
    return 0;
}
TMP int STR my_cmp(const T * a, const string<T>  & b)
{
    return 0;
}
//вставка для wchar_t
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const buffer<wchar_t> * b)
{
    return wcscmp(a->str, b->str);
}
template <>int string<wchar_t>:: my_cmp(const buffer<wchar_t> * a, const wchar_t  * b)
{
    return wcscmp(a->str, b);
}
template <>int string<wchar_t>:: my_cmp(const wchar_t * a, const string<wchar_t>  & b)
{
    return wcscmp(a, b.buf->str);
}
 
//SPIKE for char
template <>int string<char>:: my_cmp(const buffer<char> * a, const buffer<char> * b)
{
    return strcmp(a->str, b->str);
}
template <>int string<char>:: my_cmp(const buffer<char> * a, const char  * b)
{
    return strcmp(a->str, b);
}
template <>int string<char>:: my_cmp(const char * a, const string<char>  & b)
{
    return strcmp(a, b.buf->str);
}
 
TMP int STR my_cmp(const T  a, const string<T>  & b)
{
    return a - b.buf->str[0];
}
TMP int STR my_cmp(const buffer<T> * a, const T b)
{
    return a->str[0] - b;
}
 
TMP void *STR my_malloc(size_t size)
{
    void * temp = malloc((size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else
    {
        ((T *)temp)[size] = 0;
        ((T *)temp)[0] = 0;
    }
    return temp;
}
TMP void * STR my_realloc(void *str, size_t size)
{
    void * temp = realloc(str, (size + 1) * sizeof(T));
    if (!temp)
        throw std::bad_alloc();
    else 
        ((T *)temp)[size] = 0;
    return temp;
}
TMP void STR my_free(string<T> *a)
{
    if (--(a->buf->numb_copies)  == 0)
        delete (a->buf);
}
 
template class string <char>;
template class buffer<char>;
template class string <wchar_t>;
template class buffer <wchar_t>;
Error 4 error C2248: 'string<T>::XZ::XZ' : cannot access private member declared in class 'string<T>::XZ' x:\учебные\программирование 2011\шаблоны-строки\lib\lib.h 138
вроде все паблик

Добавлено через 12 минут
понял косяк, наступаю дальше.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
19.02.2012, 21:06
Помогаю со студенческими работами здесь

'MyQueue' : use of class template requires template argument list
Написал код про шаблоны. Не могу понять почему выводит ошибку во время наследования класса. ошибки 'MyQueue' : use of class template...

Ошибка компиляции: template-id does not match any template declaration
Здравствуйте. Помогите, пожалуйста: #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T maxn(T*, const int*); ...

В чем различие template <typename T> от template <class T> ?
Добрый день ! Заметил в новых книгах применение записи template &lt;typename T&gt; вместо template &lt;class T&gt; в чем же тогда фишка...

Visual Studio выдаёт ошибку при вынесении объявления функции с template в .h файл. Без template всё работает
Проект содержит три файла: Source.cpp, arrTreat.h, arrTreat.cpp. Source.cpp: #include &lt;iostream&gt; using std::cout; using...

Ошибка с django.Template.Template
Из учебника djbook: http://djbook.ru/ch04s02.html В самом начале представлен пример использования шаблонов: &gt;&gt;&gt; from django...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка. Рецензия / Мнение/ Перевод https:/ / **********/ gallery/ thinkpad-x220-tablet-porn-gzoEAjs . . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru