Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/21: Рейтинг темы: голосов - 21, средняя оценка - 4.57
381 / 352 / 113
Регистрация: 17.05.2012
Сообщений: 1,049

переопределение шаблонов

22.01.2013, 15:07. Показов 4311. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Есть такой код:

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
#ifndef ARRAY1_H
#define ARRAY1_H
 
#include <iostream>
#include <locale.h>
#include <assert.h>
using namespace std;
 
template<class V>
class Array
{
    template<class V>
    friend wostream& operator<<(wostream &, const Array<V> &);
    template<class V>
    friend wistream& operator>>(wistream &, const Array<V> &);
 
    public:
        Array(int = 10);
        Array(const Array &);
        ~Array();
        int getSize() const;
        const Array& operator=(const Array &);
 
        V operator==(const Array &) const;
        V operator!=(const Array &) const;
        V &operator[](int);
        static int getArrayCount();
 
    private:
        V *ptr;
        int size;
 
        static int ArrayCount;
};
 
template<class V>
int Array<V>::ArrayCount = 0;
 
template<class V>
Array<V>::Array(int arraySize)
{
    ++ArrayCount;
    size = arraySize;
    ptr = new V[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = 0;                 //присвоение начальных значений
}
 
template<class V>
Array<V>::Array(const Array &init)
{
    ++ArrayCount;
    size = init.size;
    ptr = new V[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = init.ptr[i];                   //копирование init в объект
}
 
template<class V>
Array<V>::~Array()
{
    --ArrayCount;
    delete []ptr;
}
 
template<class V>
int Array<V>::getSize() const {return size;}
 
template<class V>
const Array<V>& Array<V>::operator=(const Array &right)
{
    if(&right != this)
    {
        delete []ptr;
        size = right.size;
        ptr = new V[size];
        assert(ptr != 0);
 
        for(int i = 0; i < size; i++)
            ptr[i] = right.ptr[i];
    }
 
    return *this;               //позволяет = y = z
}
 
template<class V>
V Array<V>::operator ==(const Array &right) const
{
    if(size != right.size)
        return 0;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 0;
 
    return 1;
}
 
template<class V>
V Array<V>::operator !=(const Array &right) const
{
    if(size != right.size)
        return 1;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 1;
 
    return 0;
}
 
template<class V>
V &Array<V>::operator [](int subscript)
{
    assert(0 <= subscript && subscript < size);
 
    return ptr[subscript];
}
 
template<class V>
int Array<V>::getArrayCount() {return ArrayCount;}
 
template<class V>
wistream& operator>>(wistream &inpyt, const Array<V> &a)
{
    for(int i = 0; i < a.getSize(); i++)
        inpyt >> a.ptr[i];
 
    return inpyt;       //позволяет cin >> x >> y
}
 
template<class V>
wostream& operator<<(wostream &outpyt, const Array<V> &a)
{
    for(int i = 0; i < a.getSize(); i++)
    {
        outpyt << a.ptr[i] << ' ';
    }
 
    return outpyt;      //позволяет cout << x << y
}
#endif ARRAY1_H
а теперь нужно переопределить этот шаблон но уже явно для типа float...
создаю другой .h файл и делаю так:

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
#ifndef ARRAY2_H
#define ARRAY2_H
 
#include <iostream>
#include <locale.h>
#include <assert.h>
using namespace std;
 
template<int>
class Array
{
    template<int>
    friend wostream& operator<<(wostream &, const Array<int> &);
    template<int>
    friend wistream& operator>>(wistream &, const Array<int> &);
 
    public:
        Array(int = 10);
        Array(const Array &);
        ~Array();
        int getSize() const;
        const Array& operator=(const Array &);
 
        int operator==(const Array &) const;
        int operator!=(const Array &) const;
        int &operator[](int);
        static int getArrayCount();
 
    private:
        int *ptr;
        int size;
 
        static int ArrayCount;
};
 
template<int>
int Array<int>::ArrayCount = 0;
 
template<int>
Array<int>::Array(int arraySize)
{
    ++ArrayCount;
    size = arraySize;
    ptr = new int[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = 0;                 //присвоение начальных значений
}
 
template<int>
Array<int>::Array(const Array &init)
{
    ++ArrayCount;
    size = init.size;
    ptr = new int[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = init.ptr[i];                   //копирование init в объект
}
 
template<int>
Array<int>::~Array()
{
    --ArrayCount;
    delete []ptr;
}
 
template<int>
int Array<int>::getSize() const {return size;}
 
template<int>
const Array<int>& Array<T>::operator=(const Array &right)
{
    if(&right != this)
    {
        delete []ptr;
        size = right.size;
        ptr = new int[size];
        assert(ptr != 0);
 
        for(int i = 0; i < size; i++)
            ptr[i] = right.ptr[i];
    }
 
    return *this;               //позволяет = y = z
}
 
template<int>
int Array<int>::operator ==(const Array &right) const
{
    if(size != right.size)
        return 0;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 0;
 
    return 1;
}
 
template<int>
int Array<int>::operator !=(const Array &right) const
{
    if(size != right.size)
        return 1;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 1;
 
    return 0;
}
 
template<int>
int &Array<int>::operator [](int subscript)
{
    assert(0 <= subscript && subscript < size);
 
    return ptr[subscript];
}
 
template<int>
int Array<int>::getArrayCount() {return ArrayCount;}
 
template<int>
wistream& operator>>(wistream &inpyt, const Array<int> &a)
{
    for(int i = 0; i < a.getSize(); i++)
        inpyt >> a.ptr[i];
 
    return inpyt;       //позволяет cin >> x >> y
}
 
template<int>
wostream& operator<<(wostream &outpyt, const Array<int> &a)
{
    for(int i = 0; i < a.getSize(); i++)
    {
        outpyt << a.ptr[i] << ' ';
    }
 
    return outpyt;      //позволяет cout << x << y
}
 
#endif ARRAY2_H
Выдает:
C++
1
error C3855: 'Array': template parameter 'V' is incompatible with the declaration
И там дальше еще кучу ошибок... в чем может быть проблема? Заранее благодарю!
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.01.2013, 15:07
Ответы с готовыми решениями:

Перегрузка шаблонов
привет, объясните, почему вызывается первая версия шаблона? #include &lt;iostream&gt; using namespace std; template &lt;typename...

Немного шаблонов
Добрый день форумчане, у меня в порядке бреда родилась такая идея class B//базовый класс, содержит указатель на void { public: ...

Наследование шаблонов
Есть некоторый класс first, реализованный по шаблону. Можно ли от него наследовать другой класс, сохраняя при этом шаблон? Есть такой код...

7
Каратель
Эксперт С++
6610 / 4029 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
22.01.2013, 15:21
C++
1
2
template<>
class Array<int>
в остальных местах так же
2
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
22.01.2013, 15:23
Цитата Сообщение от yoghurt92 Посмотреть сообщение
переопределить этот шаблон
Переопределить нельзя, можно специализировать:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
class Array {
 
   T * ptr;
   int size;
};
 
template<>
class Array<int> {
 
   int * ptr;
   int size;
};
2
4 / 4 / 4
Регистрация: 14.09.2012
Сообщений: 64
22.01.2013, 19:27
C++
1
template void <int> f(int,int);
Использовать шаблон функции, что-бы сгенерировать определение для int.
Явное создание экземпляра. Пратта С."Язык программирования С++" стр.409.
0
381 / 352 / 113
Регистрация: 17.05.2012
Сообщений: 1,049
22.01.2013, 20:57  [ТС]
gray_fox, сделал вот так, только для float, запилил в отдельный хэдер но все равно выдает вот что:

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
#ifndef ARRAY3_H
#define ARRAY3_H
 
#include <iostream>
#include <locale.h>
#include <assert.h>
using namespace std;
 
template<>
class Array<float>
{
    template<>
    friend wostream& operator<<(wostream &, const Array<float> &);
    template<>
    friend wistream& operator>>(wistream &, const Array<float> &);
 
    public:
        Array(int = 10);
        Array(const Array &);
        ~Array();
        int getSize() const;
        const Array& operator=(const Array &);
 
        int operator==(const Array &) const;
        int operator!=(const Array &) const;
        int &operator[](int);
        static int getArrayCount();
 
    private:
        int *ptr;
        int size;
 
        static int ArrayCount;
};
 
template<>
int Array<float>::ArrayCount = 0;
 
template<>
Array<float>::Array(int arraySize)
{
    ++ArrayCount;
    size = arraySize;
    ptr = new int[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = 0;                 //присвоение начальных значений
}
 
template<>
Array<float>::Array(const Array &init)
{
    ++ArrayCount;
    size = init.size;
    ptr = new int[size];
    assert(ptr != 0);           //завершение если память не выделена
 
    for(int i = 0; i < size; i++)
        ptr[i] = init.ptr[i];                   //копирование init в объект
}
 
template<>
Array<float>::~Array()
{
    --ArrayCount;
    delete []ptr;
}
 
template<>
int Array<float>::getSize() const {return size;}
 
template<>
const Array<float>& Array<T>::operator=(const Array &right)
{
    if(&right != this)
    {
        delete []ptr;
        size = right.size;
        ptr = new int[size];
        assert(ptr != 0);
 
        for(int i = 0; i < size; i++)
            ptr[i] = right.ptr[i];
    }
 
    return *this;               //позволяет = y = z
}
 
template<>
int Array<float>::operator ==(const Array &right) const
{
    if(size != right.size)
        return 0;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 0;
 
    return 1;
}
 
template<>
int Array<float>::operator !=(const Array &right) const
{
    if(size != right.size)
        return 1;
 
    for(int i = 0; i < size; i++)
        if(ptr[i] != right.ptr[i])
            return 1;
 
    return 0;
}
 
template<>
int &Array<float>::operator [](int subscript)
{
    assert(0 <= subscript && subscript < size);
 
    return ptr[subscript];
}
 
template<>
int Array<float>::getArrayCount() {return ArrayCount;}
 
template<>
wistream& operator>>(wistream &inpyt, const Array<float> &a)
{
    for(int i = 0; i < a.getSize(); i++)
        inpyt >> a.ptr[i];
 
    return inpyt;       //позволяет cin >> x >> y
}
 
template<>
wostream& operator<<(wostream &outpyt, const Array<float> &a)
{
    wcout << "\nFloat\n";
    for(int i = 0; i < a.getSize(); i++)
    {
        outpyt << a.ptr[i] << ' ';
    }
 
    return outpyt;      //позволяет cout << x << y
}
 
#endif ARRAY3_H
И ошибки:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'operator <<' : a friend function definition cannot be a specialization of a function template
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(15) : error C3637: 'operator >>' : a friend function definition cannot be a specialization of a function template
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(37) : error C2998: 'int Array<float>::ArrayCount' : cannot be a template definition
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(49) : error C2910: 'Array<float>::{ctor}' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(61) : error C2910: 'Array<float>::{ctor}' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(68) : error C2910: 'Array<float>::~Array' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(71) : error C2910: 'Array<float>::getSize' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(74) : error C2065: 'T' : undeclared identifier
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(74) : error C2955: 'Array' : use of class template requires template argument list
1>        c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array1.h(11) : see declaration of 'Array'
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(74) : error C2955: 'Array' : use of class template requires template argument list
1>        c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array1.h(11) : see declaration of 'Array'
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(88) : error C2910: 'Array<V>::operator =' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(101) : error C2910: 'Array<float>::operator ==' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(114) : error C2910: 'Array<float>::operator !=' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(122) : error C2910: 'Array<float>::operator []' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(125) : error C2910: 'Array<float>::getArrayCount' : cannot be explicitly specialized
1>c:\users\vanya\documents\visual studio 2008\projects\templ\templ\array3.h(131) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://c:\Users\Vanya\Documents\Visual Studio 2008\Projects\templ\templ\Debug\BuildLog.htm"
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
22.01.2013, 21:09
Цитата Сообщение от yoghurt92 Посмотреть сообщение
template<> friend wostream& operator<<(wostream &, const Array<float> &);
template<> здесь не нужно. При определении методов\членов специализации тоже. И для специализации нужно знать определение самого шаблона (включить заголовочный файл с шаблоном в файл с его специализацией).
1
381 / 352 / 113
Регистрация: 17.05.2012
Сообщений: 1,049
22.01.2013, 21:14  [ТС]
gray_fox, т.е. template<> class Array<float> указываем в начале и больше template<> не используем, но почему?

все работает, спасибо
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
22.01.2013, 21:45
Цитата Сообщение от yoghurt92 Посмотреть сообщение
больше template<> не используем, но почему?
template<> нужен для указания специализации, здесь же специализируется шаблон класса, а не его методы.
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
// шаблон класса
template<typename T>
class array {
 
   // метод
   void f();
 
   // шаблон метода
   template<typename U>
   void g();
};
 
// определение метода
template<typename T>
void array<T>::f() {}
 
// определение шаблона метода
template<typename T>
template<typename U>
void array<T>::g() {}
 
// специализация шаблона метода без специализации
// шаблона класса не разрешена
// template<typename T>
// template<>
// void array<T>::g<int>() {}
 
 
// специализация шаблона класса
template<>
class array<int> {
   
   // метод
   void f();
 
   // шаблон метода
   template<typename U>
   void g();
};
 
// определение метода
void array<int>::f() {}
 
// определение шаблона метода
template<typename U>
void array<int>::g() {} 
 
// специализация шаблона метода
template<>
void array<int>::g<int>() {}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
22.01.2013, 21:45
Помогаю со студенческими работами здесь

Использование шаблонов
Здравствуйте, пытаюсь набросать элементарный пример шаблона в Visual Studio 12 и получаю ошибку компилятора: error LNK2001:...

Создание шаблонов C++
Помогите создать шаблон пожалуйста или может быть у кого нибудь уже есть данные программы. Задание 1: Работа с одномерными массивами....

запрет шаблонов
У меня есть некоторая шаблонная функция, которая определена для некоторого набора типов данныхх. Как можно сделать так, чтобы функцию...

Функции-шаблонов
1.Нужно переделать в шаблоне input - набор символов не через a = rand() % 15; , а через ручной. Помогите, пожалуйста. #include...

Экспорт шаблонов
Вопрос такой: Можно ли в Visual C++ реализовать экспорт шаблонов функций так, чтобы например в файле с именем file2.cpp иметь вот...


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

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
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
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru