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

I'm having compiler errors, and I'm not sure why. What am I doing wrong here: Hangman.cpp: set Hangman::incorrectGuesses() { // Hangman line 103 return Utils::findAll_if<c...

I’m having compiler errors, and I’m not sure why. What am I doing wrong here:

Hangman.cpp:

set<char> Hangman::incorrectGuesses()
{
     // Hangman line 103
    return Utils::findAll_if<char>(guesses.begin(), guesses.end(), &Hangman::isIncorrectGuess);
}

bool Hangman::isIncorrectGuess(char c)
{
    return correctAnswer.find(c) == string::npos;
}

Utils.h:

namespace Utils
{
    void PrintLine(const string& line, int tabLevel = 0);
    string getTabs(int tabLevel);

    template<class result_t, class Predicate>
    std::set<result_t> findAll_if(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred)
    {
        std::set<result_t> result;
              // utils line 16
        return detail::findAll_if_rec<result_t>(begin, end, pred, result);
    }
}

namespace detail
{
    template<class result_t, class Predicate>
    std::set<result_t> findAll_if_rec(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred, std::set<result_t> result)
    {
              // utils line 25
        typename std::set<result_t>::iterator nextResultElem = find_if(begin, end, pred);
        if (nextResultElem == end)
        {
            return result;
        }
        result.insert(*nextResultElem);

        return findAll_if_rec(++nextResultElem, end, pred, result);
    }
}

This produces the following compiler errors:

    algorithm(83): error C2064: term does not evaluate to a function taking 1 arguments
    algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled
    1>          with
    1>          [
    1>              _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              _Pr=bool (__thiscall Hangman::* )(char)
    1>          ]

utils.h(25) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,Predicate>(_InIt,_InIt,_Pr)' being compiled
    1>          with
    1>          [
    1>              _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              Predicate=bool (__thiscall Hangman::* )(char),
    1>              _Pr=bool (__thiscall Hangman::* )(char)
    1>          ]

utils.h(16) : see reference to function template instantiation 'std::set<_Kty> detail::findAll_if_rec<result_t,Predicate>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate,std::set<_Kty>)' being compiled
    1>          with
    1>          [
    1>              _Kty=char,
    1>              result_t=char,
    1>              Predicate=bool (__thiscall Hangman::* )(char),
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>
    1>          ]

hangman.cpp(103) : see reference to function template instantiation 'std::set<_Kty> Utils::findAll_if<char,bool(__thiscall Hangman::* )(char)>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate)' being compiled
    1>          with
    1>          [
    1>              _Kty=char,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              Predicate=bool (__thiscall Hangman::* )(char)
    1>          ]

I’m having compiler errors, and I’m not sure why. What am I doing wrong here:

Hangman.cpp:

set<char> Hangman::incorrectGuesses()
{
     // Hangman line 103
    return Utils::findAll_if<char>(guesses.begin(), guesses.end(), &Hangman::isIncorrectGuess);
}

bool Hangman::isIncorrectGuess(char c)
{
    return correctAnswer.find(c) == string::npos;
}

Utils.h:

namespace Utils
{
    void PrintLine(const string& line, int tabLevel = 0);
    string getTabs(int tabLevel);

    template<class result_t, class Predicate>
    std::set<result_t> findAll_if(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred)
    {
        std::set<result_t> result;
              // utils line 16
        return detail::findAll_if_rec<result_t>(begin, end, pred, result);
    }
}

namespace detail
{
    template<class result_t, class Predicate>
    std::set<result_t> findAll_if_rec(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred, std::set<result_t> result)
    {
              // utils line 25
        typename std::set<result_t>::iterator nextResultElem = find_if(begin, end, pred);
        if (nextResultElem == end)
        {
            return result;
        }
        result.insert(*nextResultElem);

        return findAll_if_rec(++nextResultElem, end, pred, result);
    }
}

This produces the following compiler errors:

    algorithm(83): error C2064: term does not evaluate to a function taking 1 arguments
    algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled
    1>          with
    1>          [
    1>              _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              _Pr=bool (__thiscall Hangman::* )(char)
    1>          ]

utils.h(25) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,Predicate>(_InIt,_InIt,_Pr)' being compiled
    1>          with
    1>          [
    1>              _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              Predicate=bool (__thiscall Hangman::* )(char),
    1>              _Pr=bool (__thiscall Hangman::* )(char)
    1>          ]

utils.h(16) : see reference to function template instantiation 'std::set<_Kty> detail::findAll_if_rec<result_t,Predicate>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate,std::set<_Kty>)' being compiled
    1>          with
    1>          [
    1>              _Kty=char,
    1>              result_t=char,
    1>              Predicate=bool (__thiscall Hangman::* )(char),
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>
    1>          ]

hangman.cpp(103) : see reference to function template instantiation 'std::set<_Kty> Utils::findAll_if<char,bool(__thiscall Hangman::* )(char)>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate)' being compiled
    1>          with
    1>          [
    1>              _Kty=char,
    1>              _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>,
    1>              Predicate=bool (__thiscall Hangman::* )(char)
    1>          ]

Hi guys,

I am facing «error C2064: term does not evaluate to a function taking 1 arguments» in this program during compiler.

Please help.

Cheers,
Dev

#include <iostream>
#include <cctype> //For toupper
using namespace std;

//function declarations

//public variable
//main
int main()
{
    // Variable Declarations

        char Reply = ‘ ‘;
    char ReadChar;

    int selectnum; /* defines input*/
    int GetResult; /* defines conversion input*/

        int    results[5]={0,0,0,0,0}; /* Initialise Array*/

    cout << «n    ********* Welcome to C++ Program for Managing Exam Results ********nn»; /*Displays Title*/

    cout << »    1. Read and Store Exam Resultsn»;
    cout << »    2. Sort and Display Results in Ascending Ordern»;
    cout << »    3. Calculate Fail Raten»;
    cout << »    4. Search for a particular Resultn»;
    cout << »    5. Display All Resultn»;
    cout << »    6. Exitnnn»;

    cout << »    Enter 1/2/3/4/5/6: «;
    cin>>selectnum;

    while(selectnum > 6) /* While loop to ensure no number > 6 is inputted*/
    {
        cout << «ntError! Please enter a number between 1 to 6. na»;
        cout << «n    ********* Welcome to C++ Program for Managing Exam Results ********nn»; /*Displays Title*/
        cout << »    1. Read and Store Exam Resultsn»;
        cout << »    2. Sort and Display Results in Ascending Ordern»;
        cout << »    3. Calculate Fail Raten»;
        cout << »    4. Search for a particular Resultn»;
        cout << »    5. Display All Resultn»;
        cout << »    6. Exitnnn»;
        cout << »    Enter 1/2/3/4/5/6: «;

        cin >> selectnum;
    }

    while ((selectnum > 0 )&&(selectnum < 6)) /* While loop to allow multiple selection*/
    {

        switch (selectnum) /* Switch…Case to compare a variable to several integral values */
        {
            case 1: /*Read and Store Exam Results*/
                cout << «The current Results are:n»<<endl
                     <<«{0,0,0,0,0}»;       
                cout<<«Do you wish to update the result? (Y/N): «;

                                                ReadChar(Reply);            // ERROR LINE

                Reply=toupper(Reply); //Convert to uppercase

                                while ((Reply!=’N’)&& (Reply!=’Y’))
                {
                    cout<<«nInvalid Entry. Try again.»<<endl
                        <<«Please enter Y or N ==>»;
                    ReadChar(Reply);        // ERROR LINE
                    Reply=toupper(Reply);
                }

                if (Reply == ‘Y’)
                {
                    cin >> GetResult;

                                }   
                else if (Reply==’N’)
                {
                        cout << «n    ********* Welcome to C++ Program for Managing Exam Results ********nn»; /*Displays Title*/
                        cout << »    1. Read and Store Exam Resultsn»;
                        cout << »    2. Sort and Display Results in Ascending Ordern»;
                        cout << »    3. Calculate Fail Raten»;
                        cout << »    4. Search for a particular Resultn»;
                        cout << »    5. Display All Resultn»;
                        cout << »    6. Exitnnn»;
                        cout << »    Enter 1/2/3/4/5/6: «;
                }

                                                while (selectnum > 6) /* while statement to ensure no number > 6 is inputted*/
                {
                    cout << «nnError! Please enter a number between 1 to 6. n»;
                    cout << «n    ********* Welcome to C++ Program for Managing Exam Results ********nn»; /*Displays Title*/
                    cout << »    1. Read and Store Exam Resultsn»;
                    cout << »    2. Sort and Display Results in Ascending Ordern»;
                    cout << »    3. Calculate Fail Raten»;
                    cout << »    4. Search for a particular Resultn»;
                    cout << »    5. Display All Resultn»;
                    cout << »    6. Exitnnn»;
                    cout << »    Enter 1/2/3/4/5/6: «;
                    cin >> selectnum;
                }
                break;

        }
    }
}

Could anyone help me to spot the error ? I dun even know what is wrong with my coding.

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
#include<iostream>
#include<string>
using namespace std;

void mcnuggets(int n,int *value1,int *value2);
void meal(int n,char a);
void single(int n,char a);



int main(){
	//size_o = original size, size_m = size for meal, size_a = size for A la carte
	int input[9],size_o[10],size_m[10],size_a[10],count(0),count2(0),c,f; 
	// o_letter = original letter, e_letter = extracted letter 
	char o_letter[10]={'a','A','b','c','d','e','f','g','h','i'},e_letter[10];
	bool zero(1),stop(0);
	fill_n(size_m,10,0);
	string output;
	cout<<"Welcome to McDonald's HK, what would you like to order?";
    cout<<"(A)How many of Chicken McNuggets(s) you want to order(at least 4)? ";cin>>input[0];
    cout<<"(B)How many set of McWings(s) you want to order? ";cin>>input[1];
    cout<<"(C)How many of McSpicy Chicken Filet(s) you want to order? ";cin>>input[2];
    cout<<"(D)How many of Sausage McMuffin with Egg(s) you want to order? ";cin>>input[3];
    cout<<"(E)How many of Filet - O - Fish(s) you want to order? ";cin>>input[4];
    cout<<"(F)How many of (small) Soft Drink(s) you want to order? ";cin>>input[5];
    cout<<"(G)How many of (small) Fries(s) you want to order? ";cin>>input[6];
    cout<<"(H)How many of Apple Pie(s) you want to order? ";cin>>input[7];
    cout<<"(I)How many of Ice - cream(s) you want to order? ";cin>>input[8];

	// check if order is placed
	for(int i=0;i<=9;i++){
		if(input[i]!=0) zero=0;
	}
	if(zero) cout<<"No order placed !"<<endl;

	else{

	if(input[0]==4 || (input[0]>=6 && (input[0]%3==0 || (input[0]-4)%3==0) ) ){
		if((input[0]-4)%3==0) input[0]-=4;
		if(input[0]!=4) mcnuggets(input[0],&size_o[0],&size_o[1]);
	}

	else {cout<<"No solution !"<<endl; stop=1;}
	

	//to check if nuggets of 6 or 9 contains value and store the letter
	if(!stop){
	for(int i=0;i<=1;i++){
		if(size_o[i]!=0){
			e_letter[count]=o_letter[i];
			count++;
			
		}}

	//extract the products which contains data
	for(int i=1;i<=9;i++){
		if(input[i]>0){
			size_o[count]=input[i];
			size_a[count]=size_o[count];
			e_letter[count]=o_letter[i+1];
			//if(i==5)c=count; if(i==6)f=count;
			count++;
		}}


	




	//calculate size for meal
	if(input[5]>=2 && input[6]>=2){
		c=input[5];f=input[6];
		for(int i=0;i<=count,c>=2 && f>=2;i++){
		if(o_letter[i]!='f' && o_letter[i]!='g'&& o_letter[i]!='h'&& o_letter[i]!='i'){
		size_m[i]=min(size_m[i],c/2,f/2);
		size_a[i]-=size_m[i];
		count2++;
		c-=2;f-=2;
		}
	}
    //output the plans	
	for(int i=0;i<=count;i++){
		if(size_m[i]!=0){
		meal(size_m[i],e_letter[i]);
		if(i!=count)cout<<"+";}
	}
	for(int i=0;i<=count;i++){
		if(size_a[i]!=0){
		single(size_a[i],e_letter[i]);
		if(i!=count)cout<<"+";}

	}

	}
	}
	}
      return 0;
	
}


//functions
//calculate the combinations of mcnuggets
void mcnuggets(int n,int *value1,int *value2){
	bool stop(0);
	for(int i=0;i<=n/6;i++){
		if (stop)break;  
		for(int x=0;x<=n/6;x++){ //n/6 is the largest posible no. of meals or A la carte
			if(n-i*6-x*9==0){
				*value1=i;
				*value2=x;
				stop=1;
				break;
			}
			
		}
	}
}


void meal(int n,char a){
	switch(a){
	case 'a':cout<<n<<" x M1 ($22.00)";break;
	case 'A':cout<<n<<" x M2 ($35.50)";break;
	case 'b':cout<<n<<" x M3 ($36.80)";break;
	case 'c':cout<<n<<" x M4 ($22.00)";break;
    case 'd':cout<<n<<" x M5 ($29.5)";break;
	case 'e':cout<<n<<" x M6 ($33.00)";break;
	}

	}

void single(int n,char a){
	switch(a){
	case 'a':cout<<n<<" x A1 ($17.50)";break;
	case 'A':cout<<n<<" x A2 ($35.50)";break;
	case 'b':cout<<n<<" x A3 ($20.60)";break;
	case 'c':cout<<n<<" x A4 ($20.50)";break;
    case 'd':cout<<n<<" x A5 ($9.00)";break;
	case 'e':cout<<n<<" x A6 ($10.00)";break;
	case 'f':cout<<n<<" x V1 ($5.00)";break;
	case 'g':cout<<n<<" x V2 ($5.00)";break;
	case 'h':cout<<n<<" x V3 ($5.00)";break;
	case 'i':cout<<n<<" x V4 ($5.00)";break;
	}
	}


#c #c 17 #std #filesystemwatcher

Вопрос:

Я немного занимаюсь наблюдением за файлами на C , но после некоторого рефакторинга у меня возникла проблема. В основном я понимаю, в чем проблема. Я вызываю функцию, которая на самом деле не является функцией, но я не могу найти такую вещь. Все ответы говорят о том, что есть какое-то имя, которое вызывается как функция.

Вот мой заголовок:

 #ifndef FILEWATCHER_H
#define FILEWATCHER_H
#include <unordered_map>
#include <filesystem>

namespace fs = std::filesystem;

class FileWatcher
{
    size_t currentNumberOfFiles = 0;
    fs::path pathToWatch;
    std::unordered_map<fs::path, fs::file_time_type> pathsMap;
    std::string currentTime();
public:
    FileWatcher(fs::path path);
    void start();
};
    
#endif
 

И файл .cpp:

 #pragma warning(disable : 4996)
#include "FileWatcher.h"
#include "Event.h"

std::string FileWatcher::currentTime()
{
    auto now = std::chrono::system_clock::now();
    std::time_t nowTime = std::chrono::system_clock::to_time_t(now);
    std::string currentSystemTime = std::ctime(amp;nowTime);
    return currentSystemTime;
}

FileWatcher::FileWatcher(fs::path pathToWatch)
{
    this->pathToWatch = pathToWatch;
    //create a map with last modification of a given file in the directory
    for (autoamp; file : fs::directory_iterator(this->pathToWatch))
    {
        pathsMap.emplace(file.path(), fs::last_write_time(file));
    }
}

void FileWatcher::start()
{
    while (true)
    {
        currentNumberOfFiles = std::distance(fs::directory_iterator(pathToWatch), fs::directory_iterator());

        for (std::unordered_map<fs::path, fs::file_time_type>::iterator it = pathsMap.begin(); it != pathsMap.end(); )
        {
            if (!fs::exists(it->first))
            {   
                if (currentNumberOfFiles < pathsMap.size())
                {
                    //std::cout << "File was erased" << std::endl;
                    it = pathsMap.erase(it);
                    //FileType fileType = ( ? FileType::FILE : FileType::DIRECTORY);
                    std::string time = this->currentTime();
                    Event event(EventType::DELETED, FileType::FILE, it->first, time);
                    event.printEvent();
                }
                else
                {
                    //std::cout << "Renamed" << std::endl;
                    it = pathsMap.erase(it);
                }
            }
            else
            {
                it  ;
            }
        }
        
        for (autoamp; file : fs::directory_iterator(pathToWatch))
        {
            if (!pathsMap.count(file.path()))
            {
                //std::cout << "File has been created" << std::endl;
                pathsMap.emplace(file.path(), fs::last_write_time(file));
            }
            else
            {
                if (pathsMap.at(file.path()) != fs::last_write_time(file))
                {
                    //std::cout << "File has been modified" << std::endl;
                    pathsMap.at(file.path()) = fs::last_write_time(file);
                }
            }
        }
    }
}
 

Вот список ошибок:

Изображение списка ошибок

1-я ошибка:

 Severity    Code    Description Project File    Line    Column  Category    Source  Suppression State
Error   C2056   illegal expression  ProgrammingAssignment   C:VisualStudio2019VCToolsMSVC14.28.29910includexhash 130 44      Build   
 

2-я ошибка:

 Severity    Code    Description Project File    Line    Column  Category    Source  Suppression State
Error   C2064   term does not evaluate to a function taking 1 arguments ProgrammingAssignment   C:VisualStudio2019VCToolsMSVC14.28.29910includexhash 131 53      Build   
 

Это список ошибок, на который ссылается filesystem библиотека.

 template <class _Hasher, class _Kty>
_INLINE_VAR constexpr bool _Nothrow_hash = noexcept(
    static_cast<size_t>(_STD declval<const _Hasheramp;>()(_STD declval<const _Ktyamp;>())));
 

Это вывод ошибок:

 Build started...
1>------ Build started: Project: ProgrammingAssignment, Configuration: Debug Win32 ------
1>FileWatcher.cpp
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(131,53): error C2064: term does not evaluate to a function taking 1 arguments
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(155): message : see reference to variable template 'const bool _Nothrow_hash<std::hash<std::filesystem::path>,std::filesystem::path>' being compiled
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(155): message : while compiling class template member function 'size_t std::_Uhash_compare<_Kty,_Hasher,_Keyeq>::operator ()<_Kty>(const _Keyty amp;) noexcept(<expr>) const'
1>        with
1>        [
1>            _Kty=std::filesystem::path,
1>            _Hasher=std::hash<std::filesystem::path>,
1>            _Keyeq=std::equal_to<std::filesystem::path>,
1>            _Keyty=std::filesystem::path
1>        ]
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(1218): message : see reference to variable template 'const bool _Nothrow_hash<std::_Umap_traits<std::filesystem::path,std::chrono::time_point<std::filesystem::_File_time_clock,std::chrono::duration<__int64,std::ratio<1,10000000> > >,std::_Uhash_compare<std::filesystem::path,std::hash<std::filesystem::path>,std::equal_to<std::filesystem::path> >,std::allocator<std::pair<std::filesystem::path const ,std::chrono::time_point<std::filesystem::_File_time_clock,std::chrono::duration<__int64,std::ratio<1,10000000> > > > >,0>,std::filesystem::path>' being compiled
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(1218): message : while compiling class template member function 'std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> std::_Hash<std::_Umap_traits<_Kty,std::chrono::time_point<std::filesystem::_File_time_clock,std::chrono::duration<std::chrono::system_clock::rep,std::chrono::system_clock::period>>,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>::erase<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,0>(std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>) noexcept(<expr>)'
1>        with
1>        [
1>            _Ty=std::pair<const std::filesystem::path,std::filesystem::file_time_type>,
1>            _Kty=std::filesystem::path,
1>            _Hasher=std::hash<std::filesystem::path>,
1>            _Keyeq=std::equal_to<std::filesystem::path>,
1>            _Alloc=std::allocator<std::pair<const std::filesystem::path,std::filesystem::file_time_type>>
1>        ]
1>C:VisualStudio2019VCToolsMSVC14.28.29910includexhash(130,44): error C2056: illegal expression
1>Done building project "ProgrammingAssignment.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
 

Комментарии:

1. Выдает ли ваш компилятор только коды ошибок или есть описание вместе с номером ошибки? Пожалуйста, отредактируйте свой пост с сообщением об ошибке дословно вместе с описанием.

2. Кроме того, пожалуйста, отредактируйте свой код с помощью какого-либо маркера, указывающего, на какой оператор ссылается компилятор.

3. Есть ли какой-либо способ выделить текст ошибки в буфер обмена (скопировать) и вставить в свой вопрос в виде текста? Изображения плохо масштабируются и их трудно прочитать. Ссылки будут разрушаться или блокироваться брандмауэрами.

4. Если в сообщении об ошибке компилятора указано, что строка ошибки находится на 42, вам придется указать в опубликованном коде, какой оператор является строкой 42. Вот для чего можно использовать комментарии.

5. @CuriousPanCake: В окне «Ошибка» отображаются только бесполезные сводки. Полное сообщение об ошибке находится в окне «вывод». Пожалуйста, скопируйте полный текст из окна «Вывод»: (

Ответ №1:

Сообщения об ошибках очень трудно прочитать, но в основном это сводится к отсутствию реализации std::hash<std::filesystem::path> .

std::unordered_map использует хэши для упорядочения своих элементов. По умолчанию он использует специализацию std::hash на карте key_type . Однако стандартная библиотека не обеспечивает специализацию std::hash для std::filesystem::path , отсюда и ошибки.

Итак, если вы хотите использовать std::filesystem::path в качестве key_type оф std::unordered_map , вам нужно либо:

  • предоставьте свою собственную специализацию std::hash<std::filesystem::path> , например:
 template <>
class std::hash<fs::path>
{
public:
    size_t operator()(const fs::path amp;path) const
    {
        return ... a hash of path ...;
    }
};

class FileWatcher
{
    ...
    std::unordered_map<fs::path, fs::file_time_type> pathsMap;
    ...
};
 
  • реализуйте пользовательский class / struct с an operator() , который принимает a std::filesystem::path в качестве входных данных и возвращает уникальное значение в качестве выходных. Затем вы можете явно указать этот тип в параметре std::unordered_map Hash шаблона, например:
 struct MyPathHash
{
    size_t operator()(const fs::path amp;path) const
    {
        return ... a hash of path ...;
    }
};

class FileWatcher
{
    ...
    std::unordered_map<fs::path, fs::file_time_type, MyPathHash> pathsMap;
    ...
};
 

В противном случае используйте std::map вместо этого. Он использует operator< для упорядочения свои элементы и std::filesytem::path имеет свою собственную operator< реализацию, например:

 ...
#include <map>

class FileWatcher
{
    ...
    std::map<fs::path, fs::file_time_type> pathsMap;
    ...
};
 

Комментарии:

1. Итак, я должен дать определение для operator< для fs::path и использовать его с std::map ?

2. Вам не нужно предоставлять заказ operator< fs::path , он уже есть .

3. Большое вам спасибо, это решило мою проблему.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c2039
  • Ошибка компас 2146762487
  • Ошибка компаньон консоли xbox 0x409
  • Ошибка компа reboot and select proper boot device при запуске
  • Ошибка компиляции майкрософт jscript