Ошибка компилятора c2784

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2784

Compiler Error C2784

11/04/2016

C2784

C2784

3d761fe2-881c-48bd-afae-e2e714e20473

Compiler Error C2784

‘declaration’ : could not deduce template argument for ‘type’ from ‘type’

The compiler cannot determine a template argument from the supplied function arguments.

The following sample generates C2784 and shows how to fix it:

// C2784.cpp
template<class T> class X {};
template<class T> void f(X<T>) {}

int main() {
   X<int> x;
   f(1);   // C2784

   // To fix it, try the following line instead
   f(x);
}

Still fighting with templates. In this example, despite the fact that is copied straight from a book I’m getting the following error message: Error 2 error C2784: 'IsClassT<T>::One IsClassT<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'.

This is an example from a book Templates — The Complete Guide.
(I work with Visual Studio 2010 RC).

  template<typename T> 
    class IsClassT { 
      private: 
        typedef char One; 
        typedef struct { char a[2]; } Two; 
        template<typename C> static One test(int C::*); 
        template<typename C> static Two test(…); 
      public: 
        enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; 
        enum { No = !Yes }; 
    }; 

class MyClass { 
}; 

struct MyStruct { 
}; 

union MyUnion { 
}; 

void myfunc() 
{ 
} 

enum E {e1} e; 

// check by passing type as template argument 
template <typename T> 
void check() 
{ 
    if (IsClassT<T>::Yes) { 
        std::cout << " IsClassT " << std::endl; 
    } 
    else { 
        std::cout << " !IsClassT " << std::endl; 
    } 
} 

// check by passing type as function call argument 
template <typename T> 
void checkT (T) 
{ 
    check<T>(); 
} 

int main() 
{ 
    /*std::cout << "int: "; 
    check<int>(); */

    std::cout << "MyClass: "; 
    check<MyClass>(); 
}

And although I know roughly what’s going on in this example I cannot fix this error.
Thanks for help.

Bill's user avatar

Bill

14.2k4 gold badges42 silver badges55 bronze badges

asked Mar 16, 2010 at 13:50

There is nothing we can do's user avatar

10

My compiler (MSVC2008TS) likes it if you don’t fully qualify the test expression:

enum { Yes = sizeof(test<T>(0)) == 1 }; 

But is this even legal code?

answered Mar 16, 2010 at 14:23

John Dibling's user avatar

John DiblingJohn Dibling

99.4k30 gold badges184 silver badges324 bronze badges

0

Shouldn’t this line

    enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; 

be

    enum { Yes = sizeof(IsClassT<T>::template test<T>(0)) == 1 }; 

instead?`

(And because I’m anal, I’d write sizeof(IsClassT<T>::template test<T>(0)) == sizeof(One).)

answered Mar 16, 2010 at 15:16

sbi's user avatar

5

Not exactly an answer to this question, but rather a different approach to your problem. I find it easier to do SFINAE tests in specializations rather than in functions defined in that template:

// used to pass a type tested with SFINAE
template<typename T> struct tovoid { typedef void type; };

Using it to pass a type that may be invalid:

template<typename T, typename U = void> 
struct is_class {
  static bool const value = false;
};

// if "int T::*" is a valid type, this specialization is used
template<typename T>
struct is_class<T, typename tovoid<int T::*>::type> {
  static bool const value = true;
};

This way it’s considerably shorter and the noise with sizeof and things aren’t done.

answered Mar 17, 2010 at 7:38

Johannes Schaub - litb's user avatar

AliceO

0 / 0 / 1

Регистрация: 08.11.2014

Сообщений: 6

1

18.11.2014, 10:19. Показов 1718. Ответов 2

Метки нет (Все метки)


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

имеется шаблонный список

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
#include "stdafx.h"
#include <iostream>
using namespace std;
 
template  <typename TYPE>
class list
{  
private:
 
    class node //Класс node содержит данные списка
    {
        friend class list<TYPE>;
    private:
        node *next;
        node *prev;
        TYPE val; //Данные списка
        node(): next(NULL){}
        ~node(){}
    };
    node *_begin;
    node *_end;
    node* make_node(const TYPE &data)
    {   
        node *Ptr = new node;
        Ptr->val = data;
        Ptr->prev = NULL;
        Ptr->next = NULL;
        return Ptr;
    }
 
public:
    class iterator
    {
        friend class list<TYPE>;
    private:
        node *nodeptr;
 
    public:
        iterator &operator++()
        {
            nodeptr = nodeptr->next;
            return *this;
        }
        iterator &operator--()
        {
            nodeptr = nodeptr->prev;
            return *this;
        }
 
        TYPE &iterator::operator*()
        {
            return nodeptr->val;
        }
 
        TYPE &iterator::operator->()
        {
            return nodeptr->val;
        }
    };
 
    list(): _begin(NULL), _end(NULL){}
    ~list();
 
    iterator begin()
    {
        static iterator b;
        b.nodeptr = _begin;
        return b;
    }
        
    iterator end()
    {
        static iterator e;
        e.nodeptr = _end; 
        return e;
    }
 
    void push_front(const TYPE);
    TYPE ReadFromPosition(int);
    bool pop(iterator);
    int empty() const; 
    void push_back(const TYPE );
    void clear();
};
 
template <typename TYPE>
list<TYPE>::~list()
{
    clear();
}
 
//Проверено
template <typename TYPE>
void list<TYPE>::push_front(const TYPE data)
{
    node *NewPtr = make_node(data);
    if(empty())
    {
        _begin = _end = NewPtr;
    }
    else 
    {
        NewPtr->next = _begin;
        _begin = NewPtr;
    }
}
 
template <typename TYPE>
void list<TYPE>::clear()
{
    node *current;
    current = _begin;
    node *to_delete = NULL;
    if(!empty())
    {
        while(current != NULL)
        {
            to_delete = current;
            current = current->next;
            delete to_delete;
        }
    }
}
 
template <typename TYPE>
void list<TYPE>::push_back(const TYPE data)
{
    node *NewPtr = make_node(data);
    if(empty())
        _begin = _end = NewPtr;
    else 
    {
        _end->next = NewPtr;
        _end = NewPtr;
    }
}
 
template <typename TYPE>
bool list<TYPE>::pop(iterator pos)
{
    int temp = 0,temp1 = 0;
    node *NewPtr = _begin;
    node *TempPtr = _begin;
    node *TempPtr1 = _begin;
    node *TempPtr2 = _begin;
    if(empty())
        return false;
    else
    {
        while(NewPtr->next)
        {
            temp ++;
            NewPtr = NewPtr->next;
        }
        if(temp < pos || pos < 0)
        {
            cout<<"Удаление невозможно"<<endl;
            return false;
        }
        while(temp1! = pos)  
        {
            TempPtr = TempPtr->next;
            temp1 ++;
        }
        if(pos == 0)
        {
            _begin = TempPtr->next;
            delete TempPtr;
            TempPtr = _begin;
            return true;
        }
        if(TempPtr == _end) 
        {
            while(TempPtr1->next! = _end) 
                TempPtr1 = TempPtr1->next;
            delete _end;
            _end = TempPtr1;
            _end->next = NULL;
            return true;
        }
        while(TempPtr2->next! = TempPtr) 
            TempPtr2 = TempPtr2->next;
        TempPtr2->next = TempPtr->next;
        delete TempPtr;
        return true;
 
    }
}
 
template <typename TYPE>
TYPE list<TYPE>::ReadFromPosition(int pos)
{
    int temp = 0,temp1 = 0;
    node *NewPtr = _begin;
    node *TempPtr = _begin;
    if(empty()) return NULL;
    while(NewPtr) {temp ++;NewPtr = NewPtr->next;}
    if(pos>temp || pos<0) return NULL;
    if(pos == 0) return _begin->val;
     pos --; 
    while(pos)
    {
        pos --; 
        TempPtr = TempPtr->next;         
    }
    return TempPtr->val;
}
//Проверено
template <typename TYPE>
int list<TYPE>::empty() const
{
    if(_begin == NULL)
        return 1;
    else return 0;
}
 
void main()
{
    list<int> l;
    int new_int, c;
    cout<<"Enter list"<<endl;
    for(int c = 0; c < 5; c++)
    {
        cout<<(c + 1)<<endl;
        cin>>new_int;
        l.push_back(new_int);
    }
    list<int>::iterator it = l.begin();
    for(;it != l.end(); it ++) //в этом месте ошибка
        cout<<*it<<endl;
}

error C2784: ‘bool std::operator !=(const std::istreambuf_iterator<_Elem,_Traits> &,const std::istreambuf_iterator<_Elem,_Traits> &)’ : could not deduce template argument for ‘const std::istreambuf_iterator<_Elem,_Traits> &’ from ‘list<TYPE>::iterator’
1> with
1> [
1> TYPE=int
1> ]



0



Вездепух

Эксперт CЭксперт С++

10916 / 5911 / 1615

Регистрация: 18.10.2014

Сообщений: 14,859

18.11.2014, 10:26

2

Цитата
Сообщение от AliceO
Посмотреть сообщение

could not deduce template argument

Ну так а оператор ‘!=’ вы для своего итератора определили? Не определили.
А пользоваться ‘!=’ пытаетесь? Пытаетесь.

Компилятор в отчаянии пытается приспособить какой-то другой оператор ‘!=’, но у него не получается. Поэтому ошибка.

Вперед определять операторы ‘==’ и ‘!=’ для вашего итератора.



0



AliceO

0 / 0 / 1

Регистрация: 08.11.2014

Сообщений: 6

18.11.2014, 18:05

 [ТС]

3

Спасибо за ответ.
Вот волшебство, дописываю в методы итератора

C++
1
2
3
4
5
6
7
    bool iterator::operator!=(iterator compare)
        {
            if(this->nodeptr != compare.nodeptr)
                return true;
            else
                return false;
        }

и

fatal error C1001: An internal error has occurred in the compiler

Добавлено через 16 минут
ессс! работает
спасибо ещё раз



0



  • Forum
  • General C++ Programming
  • Error C2784 — Please Help!

Error C2784 — Please Help!

Hi there, I’m new to this forum and pretty new to c++ as well and I can’t seem to get this error figured out. Here is the full error message:

C2784: ‘std::basic_istream<_Elem,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &&,std::basic_string<_Elem,_Traits,_Alloc> &)’ : could not deduce template argument for ‘std::basic_istream<_Elem,_Traits> &&’ from ‘std::ostream’

Here is my C++ code:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()

{

string name;
double roomcharge,extracharge,total;
double roomnum,numofdays;
const double roomrate=125;

cout << fixed;

cout << «Please fill in the following information to output the Total room charges, and an invouce for the guest: » << endl << endl;
cout << «Customer Name: «;
getline(cin, name);
cout << «Room Number: «;
cin >> roomnum;
cout << «Number of Days Stayed: «;
cin >> numofdays;
cout << «Extra Charges: «;
cin >> extracharge;

roomcharge=roomrate*numofdays;
total=roomcharge+extracharge;

cout << «Star Hotel Customer Invoice: «;
cout << «Customer Name: «;

system(«pause»);

}

My Project is still incomplete at the moment, but I don’t want to continue until I get this error fixed.

Any help would be appreciated, thanks in advance.

Since you don’t have something like cout >> name ; anywhere in your code, you should not be getting this error.

Hm, well that’s really weird because it’s still giving me issues. I think I’ll start a new project in Visual Studio and re-enter the code. Thanks for your input.

I’ll post my results here after trying a new project.

I expect the code you think you’re compiling is not the code you are compiling.

Moschops you may be right. I made a new project and just pasted the same code in, and it built successfully. No idea how or why, but it’s fine now. Thanks for all of the help :)

I didn’t think I had any errors in my code >.> <.<

Topic archived. No new replies allowed.

Hi everyone,

Can someone help me with my program? I’ve been working on it for awhile and still cant get it to work. Here’s the listing:

#pragma warning (disable : 4786) //disable warning about truncation of string data
#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include «masterheader.h»

using namespace std;

//type definitions
typedef multiset <MasterHeader> typeMH;

//sets up output file for writing
//Postcondition: The output file has been created with
//     name read in from the keyboard
void setUpFiles(ofstream& os);

//reads input from input file
//Postcondition: input file read into the object of class MasterHeader
void readFile();

void main()
{
 ofstream outFile; //writes output to file

 typeMH objContainer; //multiset container of type MasterHeader
 typeMH::const_iterator objContIter;

 //setup output file
 setUpFiles(outFile);

//Record 2.
 MasterHeader obj2;
 obj2.LastName = «War Hammer»;
 obj2.FirstName = «Blessed Qiraji «;
 obj2.SSN = 987654321;
 obj2.Street = «234 Stormwind Street»;
 obj2.City = «Darnassus»;
 obj2.State = «KA»;
 obj2.Zip = 12345;
 obj2.RateOfPay = 405.45;
 obj2.NumOfDependant = 2;

objContainer.insert(obj2);

//printing the objects to a file
 for (objContIter = objContainer.begin(); objContIter != objContainer.end(); objContIter++)
 {
  outFile << *objContIter << endl;
 }

 outFile.close();
}

void setupFiles (ofstream& os)
{
 string outFileName;
 cout << «Please enter the path for the output file: «;
 cin >> outFileName;
 os.open (outFileName.c_str(), ios::out);
}

I keep getting the c2784 error everytime i compile. Is there anything wrong with this? I’m following my instructor’s code exactly the same as it is but I get this error.

c:program filesmicrosoft visual studiovc98includefunctional(86) : error C2784: ‘bool __cdecl std::operator <(const class std::multiset<_K,_Pr,_A> &,const class std::multiset<_K,_Pr,_A> &)’ : could not deduce template argument for ‘const class s
td::multiset<_K,_Pr,_A> &’ from ‘const class MasterHeader’
        c:program filesmicrosoft visual studiovc98includefunctional(86) : while compiling class-template member function ‘bool __thiscall std::less<class MasterHeader>::operator ()(const class MasterHeader &,const class MasterHeader &) const’

Any help will be greatly appreciated. Thx in advance, guys.

P.S.: I didn’t list the header and implementation file. Please let me know if they’re needed

У меня проблема с некоторыми моими операторами. Операторы в моем поиске и удалении слов. В поиске я пытаюсь проверить, соответствует ли слово в моем списке поисковому слову. В deleteWord я пытаюсь проверить, что слово, которое я хочу удалить, идеально совпадает со словом в моем списке, а затем удалить его.

Я посмотрел, как исправить мой оператор, но я не понимаю. Заранее спасибо.

Некоторые ошибки:

Ошибка 1 ошибка C2784: ‘bool std :: opeator> = (const std :: basic_string<_Elem, _Traits, _Alloc> &, const_Elem *): не удалось вывести аргумент шаблона для ‘const_Elem *’ для ‘const LinkedList’

Ошибка 2 ошибка C2784: ‘bool std :: operator> = (const _Elem *, const std :: basic_string<_Elem, _Traits, _Alloc> &) ‘: не удалось вывести аргумент шаблона для’ const _Elem * ‘из’ std :: string ‘

Ошибка 3 ошибка C2784: ‘bool std :: operator> = (const std :: basic_string<_Elem, _Traits, _Alloc> &, const std :: basic_string<_Elem, _Traits, _Alloc> &) ‘: не удалось вывести аргумент шаблона для’ const std :: basic_string<_Elem, _Traits, _Alloc> &’из’ const LinkedList ‘

Ошибка 29 ошибка C2678: двоичный файл «==»: не найден оператор, который принимает левый операнд типа «std :: string» (или нет приемлемого преобразования)

Ошибка 59 IntelliSense: ни один оператор «==» не соответствует этим операндам

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <string>
#include <iostream>

using namespace std;

//Definition of the node
struct linkedList{ //linked list
string word;  //node holds string word
linkedList *next; //points to next node
linkedList *prev; //points to prev node
};

class LinkedList{
public:
LinkedList(); //default const
~LinkedList(); //destructor
const LinkedList& operator = (const LinkedList &); //overload the assignment operator
void initializeList(); //func to init list to an empty state
void read();
void printForward(linkedList *firstWord);
void printBackward(linkedList *lastWord);
void insert();
bool search(const LinkedList& searchItem) const;
void deleteWord(const LinkedList& deleteItem);
void clear();
protected:
int count;
linkedList *firstWord; //pointer to the first node
linkedList *lastWord; //pointer to the last node
};

LinkedList::LinkedList()
{
firstWord = NULL;
lastWord = NULL;
count = 0;
}
...
... //more code
...
bool LinkedList::search(const LinkedList& searchItem) const
{
bool found = false;

linkedList *temp; //pointer to traverse list
temp = firstWord;

while (temp != NULL && !found)
if (temp->word >= searchItem)
found = true;
else
temp = temp->next;
if (found)
found = (temp->word == searchItem); //test for equality
return found;
}

void LinkedList::deleteWord(const LinkedList& deleteItem)
{
linkedList *temp; //pointer to traverse the list
linkedList *trailTemp; ///pointer just before temp
bool found;

if (firstWord == NULL)
cout << "Cannot delete from an empty list." << endl;
else if (firstWord->word == deleteWord){ //node to be deleted is the firstWord
temp = firstWord;
firstWord = firstWord->next;

if (firstWord != NULL)
firstWord->prev = NULL;

else
lastWord = NULL;

count--;
delete temp;
}
else{
found = false;
temp = firstWord;

while (temp !=NULL && !found) //search the list
if (temp->word >= deleteWord)
found = true;
else
temp = temp->next;

if (temp == NULL)
cout << "The word to be deleted is not in the list." << endl;
else if (temp->word == deleteWord){ //check for equality
trailTemp = temp->prev;
trailTemp->next = temp->next;

if (temp->next != NULL)
temp->next->prev = trailTemp;

if (temp == lastWord)
lastWord = trailTemp;

count--;
delete temp;
}
else
cout << "The word to be deleted is not in the list." << endl;
}
}
...
... //more code
...
#endif

-2

Решение

Эта строка:

if (temp->word >= searchItem)

сравнивает std::string с LinkedList, Вы хотите сравнить word в temp со строкой.

Измените функцию на:

bool LinkedList::search(const std::string& searchItem) const

Большинство других ваших ошибок являются вариациями на эту тему.

Редактировать: ошибка LinkedList за linkedList — пожалуйста, не указывайте структуру и класс с тем же именем, но в разных случаях. Это очень запутанно.

1

Другие решения

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c2731
  • Ошибка компиляции для платы arduino nano как исправить
  • Ошибка компилятора c2679
  • Ошибка компиляции для платы arduino nano every
  • Ошибка компилятора c2678