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.
|
|
#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
с anoperator()
, который принимает astd::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. Большое вам спасибо, это решило мою проблему.