How can I solve the following problems in log4cpp? - visual-c++

I'm trying to compile log4cpp in visual studio 2008 but I'm getting some errors like these:
Error 26 error C2664: 'ReportEventW' : cannot convert parameter 8 from 'const char *[1]' to 'LPCWSTR *' ...\testlog4cppdll\log4cpp\src\nteventlogappender.cpp 64
Error 19 error C2676: binary '+' : 'std::basic_string<_Elem,_Traits,_Ax>' does not define this operator or a conversion to a type acceptable to the predefined operator ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 11 error C2782: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : template parameter '_Elem' is ambiguous ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 10 error C2782: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem)' : template parameter '_Elem' is ambiguous ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 18 error C2784: 'std::_Revranit<_RanIt,_Base> std::operator +(_Diff,const std::_Revranit<_RanIt,_Base> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 16 error C2784: 'std::_String_const_iterator<_Elem,_Traits,_Alloc> std::operator +(_String_const_iterator<_Elem,_Traits,_Alloc>::difference_type,std::_String_const_iterator<_Elem,_Traits,_Alloc>)' : could not deduce template argument for 'std::_String_const_iterator<_Elem,_Traits,_Alloc>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 15 error C2784: 'std::_String_iterator<_Elem,_Traits,_Alloc> std::operator +(_String_iterator<_Elem,_Traits,_Alloc>::difference_type,std::_String_iterator<_Elem,_Traits,_Alloc>)' : could not deduce template argument for 'std::_String_iterator<_Elem,_Traits,_Alloc>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 7 error C2784: 'std::_Vb_const_iterator<_Sizet,_Difft,_MycontTy> std::operator +(_Difft,std::_Vb_const_iterator<_Sizet,_Difft,_MycontTy>)' : could not deduce template argument for 'std::_Vb_const_iterator<_Sizet,_Difft,_MycontTy>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 6 error C2784: 'std::_Vb_iterator<_Sizet,_Difft,_MycontTy> std::operator +(_Difft,std::_Vb_iterator<_Sizet,_Difft,_MycontTy>)' : could not deduce template argument for 'std::_Vb_iterator<_Sizet,_Difft,_MycontTy>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 9 error C2784: 'std::_Vector_const_iterator<_Ty,_Alloc> std::operator +(_Vector_const_iterator<_Ty,_Alloc>::difference_type,std::_Vector_const_iterator<_Ty,_Alloc>)' : could not deduce template argument for 'std::_Vector_const_iterator<_Ty,_Alloc>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 8 error C2784: 'std::_Vector_iterator<_Ty,_Alloc> std::operator +(_Vector_iterator<_Ty,_Alloc>::difference_type,std::_Vector_iterator<_Ty,_Alloc>)' : could not deduce template argument for 'std::_Vector_iterator<_Ty,_Alloc>' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 13 error C2784: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'std::basic_string<_Elem,_Traits,_Ax>' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 12 error C2784: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(const _Elem,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 14 error C2784: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Error 17 error C2784: 'std::reverse_iterator<_RanIt> std::operator +(_Diff,const std::reverse_iterator<_RanIt> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'WCHAR [260]' ...\testlog4cppdll\log4cpp\src\dailyrollingfileappender.cpp 127
Here is the code:
hFind = FindFirstFile(LPTSTR(pattern.c_str()), &ffd); //Ahrost
if (hFind != INVALID_HANDLE_VALUE) {
do {
struct stat statBuf;
const std::string fullfilename = dirname + PATHDELIMITER + ffd.cFileName;
int res = ::stat(fullfilename.c_str(), &statBuf);
if (res != -1 && statBuf.st_mtime < oldest && !(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
std::cout << "Deleting " << fullfilename << "\n";
::unlink(fullfilename.c_str());
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
// [XXX] some kind of error happened
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
The entire source of file is:
#include "PortabilityImpl.hh"
#ifdef LOG4CPP_HAVE_IO_H
# include <io.h>
#endif
#ifdef LOG4CPP_HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <log4cpp/DailyRollingFileAppender.hh>
#include <log4cpp/Category.hh>
#include <log4cpp/FactoryParams.hh>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <time.h> //Ahrost
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#include <iomanip>
#endif
#ifndef WIN32 // only available on Win32
#include <dirent.h>
#endif
namespace log4cpp {
unsigned int DailyRollingFileAppender::maxDaysToKeepDefault = 30;
DailyRollingFileAppender::DailyRollingFileAppender(const std::string& name,
const std::string& fileName,
unsigned int maxDaysToKeep,
bool append,
mode_t mode) :
FileAppender(name, fileName, append, mode),
_maxDaysToKeep(maxDaysToKeep != 0 ? maxDaysToKeep : maxDaysToKeepDefault) {
struct stat statBuf;
int res;
time_t t;
// obtain last modification time
res = ::stat(fileName.c_str(), &statBuf);
if (res < 0) {
t = time(NULL);
} else {
t = statBuf.st_mtime;
}
#ifndef WIN32 // only available on Win32
localtime_r(&t, &_logsTime);
#else
localtime_s(&_logsTime, &t);
#endif
}
void DailyRollingFileAppender::setMaxDaysToKeep(unsigned int maxDaysToKeep) {
_maxDaysToKeep = maxDaysToKeep;
}
unsigned int DailyRollingFileAppender::getMaxDaysToKeep() const {
return _maxDaysToKeep;
}
void DailyRollingFileAppender::rollOver()
{
std::ostringstream filename_s;
::close(_fd);
filename_s << _fileName << "." << _logsTime.tm_year + 1900 << "-"
<< std::setfill('0') << std::setw(2) << _logsTime.tm_mon + 1 << "-"
<< std::setw(2) << _logsTime.tm_mday << std::ends;
const std::string lastFn = filename_s.str();
::rename(_fileName.c_str(), lastFn.c_str());
_fd = ::open(_fileName.c_str(), _flags, _mode);
const time_t oldest = time(NULL) - _maxDaysToKeep * 60 * 60 * 24;
#ifndef WIN32
#define PATHDELIMITER "/"
#else
#define PATHDELIMITER "\\"
#endif
// iterate over files around log file and delete older with same prefix
const std::string::size_type last_delimiter = _fileName.rfind(PATHDELIMITER);
const std::string dirname((last_delimiter == std::string::npos)? "." : _fileName.substr(0, last_delimiter));
const std::string filname((last_delimiter == std::string::npos)? _fileName : _fileName.substr(last_delimiter+1, _fileName.size()-last_delimiter-1));
#ifndef WIN32 // only available on Win32
struct dirent **entries;
int nentries = scandir(dirname.c_str(), &entries, 0, alphasort);
if (nentries < 0)
return;
for (int i = 0; i < nentries; i++) {
struct stat statBuf;
int res = ::stat(entries[i]->d_name, &statBuf);
if ((res == -1) || (!S_ISREG(statBuf.st_mode))) {
free(entries[i]);
continue;
}
if (statBuf.st_mtime < oldest && strstr(entries[i]->d_name, filname.c_str())) {
const std::string fullfilename = dirname + PATHDELIMITER + entries[i]->d_name;
::unlink(fullfilename.c_str());
std::cout << " Deleting " << fullfilename.c_str() << std::endl;
}
free(entries[i]);
}
free(entries);
#else
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
const std::string pattern = _fileName + "*";
hFind = FindFirstFile(LPTSTR(pattern.c_str()), &ffd); //Ahrost
if (hFind != INVALID_HANDLE_VALUE) {
do {
struct stat statBuf;
const std::string fullfilename = dirname + PATHDELIMITER + ffd.cFileName;
int res = ::stat(fullfilename.c_str(), &statBuf);
if (res != -1 && statBuf.st_mtime < oldest && !(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
std::cout << "Deleting " << fullfilename << "\n";
::unlink(fullfilename.c_str());
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
// [XXX] some kind of error happened
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
#endif
}
void DailyRollingFileAppender::_append(const log4cpp::LoggingEvent &event)
{
struct tm now;
time_t t = time(NULL);
#ifndef WIN32 // only available on Win32
bool timeok = localtime_r(&t, &now) != NULL;
#else
bool timeok = localtime_s(&now, &t) == 0;
#endif
if (timeok) {
if ((now.tm_mday != _logsTime.tm_mday) ||
(now.tm_mon != _logsTime.tm_mon) ||
(now.tm_year != _logsTime.tm_year)) {
rollOver();
_logsTime = now;
}
}
log4cpp::FileAppender::_append(event);
}
std::auto_ptr<Appender> create_daily_roll_file_appender(const FactoryParams& params)
{
std::string name, filename;
bool append = true;
mode_t mode = 664;
unsigned int max_days_keep = 0;
params.get_for("daily roll file appender").required("name", name)("filename", filename)("max_days_keep", max_days_keep)
.optional("append", append)("mode", mode);
return std::auto_ptr<Appender>(new DailyRollingFileAppender(name, filename, max_days_keep, append, mode));
}
}
Above source belong to DailyRollingFileAppender.cpp file which is one of the log4cpp files.

Your problem is mix-up of narrow and wide strings.
Your use of character types with letter T in the name (like LPTSTR) implies that the code can work with either narrow or wide chars, depending on the _UNICODE setting. However, you use std::string types too, which are explicitly narrow, and tring literals without wide-char specifier L.
If your code SHOULD be available in both narrow and wide favors, make sure you use TEXT() or _T() macros to form the appropriate string.

Related

Getting weird compiler errors while compiling my own "allocator<>" with MSVC 2022 in Debug-mode

I need an std::allocator<> compliant allocator with page-aligned allocation and preferrably no memory-pooling for very large allocations. Another requirement is that the allocator should have a non-standard reset()-method to reset a row of pages that the pages become discardable by the kernel if you have a row of trivial data types.
I wrote such an allocator which I post here below completely since I think others could use the allocator also if they also have this certain allocation constraints.
#pragma once
#if defined(_WIN32)
#include <Windows.h>
#elif defined(__unix__)
#include <unistd.h>
#include <sys/mman.h>
#else
#error platform not supported
#endif
#include <cstddef>
#include <type_traits>
#include <memory>
#include <utility>
#include <atomic>
#include <cassert>
#include <new>
#if !defined(NDEBUG)
#include <bit>
#endif
#include <utility>
template <typename T>
struct virtual_allocator
{
using allocator_type = virtual_allocator;
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using propagate_on_container_move_assignment = std::false_type;
constexpr virtual_allocator() noexcept {}
constexpr virtual_allocator( virtual_allocator const & ) noexcept {}
static value_type *allocate( std::size_t n );
static void deallocate( value_type *p, std::size_t n ) noexcept;
static void reset( void *p, std::size_t n )
requires (sizeof(T) == std::bit_floor( sizeof(T) )) && std::is_trivial_v<T>;
static std::size_t get_page_size();
#if defined(__cpp_lib_allocate_at_least)
static std::allocation_result<value_type *> allocate_at_least( std::size_t n );
#endif
private:
using alloc_ret_t = std::pair<value_type *, std::size_t>;
static alloc_ret_t allocateAtLeast( std::size_t n );
static std::size_t getPageSize();
};
template <typename T>
typename virtual_allocator<T>::value_type *virtual_allocator<T>::allocate( std::size_t n )
{
return allocateAtLeast( n ).first;
}
template <typename T>
void virtual_allocator<T>::deallocate( value_type *p, std::size_t n ) noexcept
{
std::size_t pageSize = getPageSize();
assert(n * pageSize / pageSize == n);
n = n * pageSize + pageSize - 1 & -(ptrdiff_t)pageSize;
#if defined(_WIN32)
bool succ = (bool)VirtualFree( p, 0, MEM_RELEASE );
#elif defined(__unix__)
bool succ = !munmap( p, n );
#endif
assert(succ);
}
#if defined(__cpp_lib_allocate_at_least)
template <typename T>
std::allocation_result<typename virtual_allocator<T>::value_type *> virtual_allocator<T>::allocate_at_least( std::size_t n )
{
auto ret = allocateAtLeast( n );
return std::allocation_result<value_type *>( ret.first, ret.second );
}
#endif
template <typename T>
typename virtual_allocator<T>::alloc_ret_t virtual_allocator<T>::allocateAtLeast( std::size_t n )
{
using namespace std;
if( n * sizeof(value_type) / sizeof(value_type) != n )
throw bad_alloc();
size_t pageSize = getPageSize();
n = n * sizeof(value_type) + pageSize - 1 & -(ptrdiff_t)pageSize;
#if defined(_WIN32)
value_type *p = (value_type *)VirtualAlloc( nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE );
#elif defined(__unix__)
value_type *p = (value_type *)mmap( nullptr, n, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0 );
#endif
if( !p ) [[unlikely]]
throw bad_alloc();
return alloc_ret_t( p, n / sizeof(value_type) );
}
template <typename T>
void virtual_allocator<T>::reset( void *p, std::size_t n )
requires (sizeof(T) == std::bit_floor( sizeof(T) )) && std::is_trivial_v<T>
{
using namespace std;
if( ((size_t)p | n) & getPageSize() - 1 || n * sizeof(value_type) / sizeof(value_type) != n ) [[unlikely]]
throw bad_alloc();
#if defined(_WIN32)
bool succ = (bool)VirtualAlloc( p, n, MEM_RESET, PAGE_READWRITE );
#elif defined(__unix__)
bool succ = !madvise( p, n, MADV_DONTNEED );
#endif
assert(succ);
}
template <typename T>
inline
std::size_t virtual_allocator<T>::get_page_size()
{
return getPageSize();
}
template <typename T>
inline
std::size_t virtual_allocator<T>::getPageSize()
{
using namespace std;
static atomic<size_t> aPageSize( 0 );
size_t pageSize = aPageSize.load( memory_order_relaxed );
if( !pageSize ) [[unlikely]]
{
#if defined(_WIN32)
SYSTEM_INFO si;
GetSystemInfo( &si );
pageSize = si.dwPageSize;
#elif defined(__unix__)
pageSize = sysconf( _SC_PAGESIZE );
#endif
assert(pageSize && pageSize == bit_floor( pageSize ));
aPageSize.store( pageSize, memory_order_relaxed );
}
return pageSize;
}
The testing code compiles fine with g++ 11.1.0 and clang++ 13 under Linux. Under Windows it compiles if you have a "Release" compile but not in "Debug" mode. I get some weird errors for which I don't have any clue what they're abut.
Severity Code Description Project File Line Suppression State
Error C2440 'static_cast': cannot convert from 'virtual_allocator<array_t>' to 'virtual_allocator<_Newfirst>' virtual_allocator C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector 595
Error C2530 '_Alproxy': references must be initialized virtual_allocator C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector 595
Error C3536 '_Alproxy': cannot be used before it is initialized virtual_allocator C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector 596
Error C2672 '_Delete_plain_internal': no matching overloaded function found virtual_allocator C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector 596
Error C2893 Failed to specialize function template 'void std::_Delete_plain_internal(_Alloc &,_Alloc::value_type *const ) noexcept' virtual_allocator C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector 596
Although I think the code would be helpful for other C++-developers I don't post this with any C++-tags. That's while if others search such an allcator they'll find it by googling anyway and my question is only related to Visual C++.
Yeah, Igor got it ! It was the missing templated constructor.
template<typename T2>
constexpr virtual_allocator( virtual_allocator<T2> const & ) noexcept {}

Pass a lamda expression in a thread pool

I try yo compile in C++11 the following piece of code without success. My goal is to use lambda expression instead of bind in order to fill a queue with tasks.
Could you please help me?
Is any case to create a dangling reference ?
#include <iostream>
#include <functional>
#include <queue>
using namespace std;
std::queue<std::function<void()>> funcs;
class A
{
public:
void foo(int a )
{
cout << "Hello word" << endl;
}
};
class ThePool
{
public:
template<typename _Callable, typename Object, typename... _Args>
void QueueFunction(_Callable __f, Object obj, _Args... __args)
{
funcs.push([=]()
{
(obj.*__f)((__args...));
});
}
void print(int i )
{
cout << "Hello Word"<< i <<endl;
}
};
int main(int argc, char** argv) {
ThePool t;
A a ;
t.QueueFunction(&A::foo,a,5);
std::function<void()> func = funcs.back();
func();
return 0;
}
The error that is generated is the following
main.cpp:24:38: error:
parameter packs not expanded with '...':
(obj.__f)((__args...));
^ main.cpp:24:38: note: '__args' main.cpp:24:44: error: expected ')' before '...' token
(obj.__f)((__args...));
^ main.cpp:24:49: error: expected ')' before ';' token
(obj.*__f)((__args...));
^ main.cpp: In function 'int main(int, char**)': main.cpp:39:45: error: conversion
from 'std::function' to non-scalar type
'std::function' requested
std::function func = funcs.back();
^ main.cpp: In instantiation of 'struct ThePool::QueueFunction(_Callable, Object,
_Args ...) [with _Callable = void (A::)(int); Object = A; _Args = {int}]::__lambda0': main.cpp:22:12: required from 'void
ThePool::QueueFunction(_Callable, Object, _Args ...) [with _Callable =
void (A::)(int); Object = A; _Args = {int}]' main.cpp:38:32:
required from here main.cpp:24:38: error: using invalid field
'ThePool::QueueFunction(_Callable, Object, _Args
...)::__lambda0::____args'
(obj.*__f)((__args...));

error when use std::thread in Class

I tried to use std::thread in Visual Studio 2013. It works all right like this.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono> // std::chrono::seconds
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <vector>
void thread_task(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "hello thread "
<< std::this_thread::get_id()
<< " paused " << n << " seconds" << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::thread> threads;
std::cout << "Spawning 5 threads...\n";
for (int i = 0; i < 5; i++) {
threads.emplace_back( std::thread(thread_task, i + 1));
}
std::cout << "Done spawning threads! Now wait for them to join\n";
for (auto& t : threads) {
t.join();
}
std::cout << "All threads joined.\n";
return 0;
}
but when I tried to make thread in a Class, I met some compiling errors.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono> // std::chrono::seconds
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <vector>
class MyClass
{
public:
MyClass();
void thread_task(int n);
~MyClass();
private:
};
MyClass::MyClass()
{
std::vector<std::thread> threads;
std::cout << "Spawning 5 threads...\n";
for (int i = 0; i < 5; i++) {
threads.emplace_back(std::thread(&MyClass::thread_task, i + 1));
}
std::cout << "Done spawning threads! Now wait for them to join\n";
for (auto& t : threads) {
t.join();
}
std::cout << "All threads joined.\n";
}
void MyClass::thread_task(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "hello thread "
<< std::this_thread::get_id()
<< " paused " << n << " seconds" << std::endl;
}
MyClass::~MyClass(){}
int _tmain(int argc, _TCHAR* argv[])
{
MyClass test();
return 0;
}
The error messages are copied below.
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(1149): error C2064: term does not evaluate to a function taking 1 arguments
1> class does not define an 'operator()' or a user defined conversion operator to a pointer-to-function or reference-to-function that takes appropriate number of arguments
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(1137) : see reference to function template instantiation 'void std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>::_Do_call<,0>(std::tuple<>,std::_Arg_idx<0>)' being compiled
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(1137) : see reference to function template instantiation 'void std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>::_Do_call<,0>(std::tuple<>,std::_Arg_idx<0>)' being compiled
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thr\xthread(195) : see reference to function template instantiation 'void std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>::operator ()<>(void)' being compiled
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thr\xthread(195) : see reference to function template instantiation 'void std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>::operator ()<>(void)' being compiled
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thr\xthread(192) : while compiling class template member function 'unsigned int std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *)'
1> with
1> [
1> _Target=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thr\xthread(187) : see reference to function template instantiation 'unsigned int std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *)' being compiled
1> with
1> [
1> _Target=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thr\xthread(205) : see reference to class template instantiation 'std::_LaunchPad<_Target>' being compiled
1> with
1> [
1> _Target=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\thread(49) : see reference to function template instantiation 'void std::_Launch<std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>>(_Thrd_t *,_Target &&)' being compiled
1> with
1> [
1> _Target=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall MyClass::* )(int),void,MyClass,int>,int>
1> ]
1> d:\projects\consoleapplication2\consoleapplication2\consoleapplication2.cpp(29) : see reference to function template instantiation 'std::thread::thread<void(__thiscall MyClass::* )(int),int>(_Fn &&,int &&)' being compiled
1> with
1> [
1> _Fn=void (__thiscall MyClass::* )(int)
1> ]
1>
What cause the problem?
Thanks #malchemist, when add this solve the problem. But it makes me confused this piece of codecode error still got some compiling errors even written just like the answer shows.
Can anyone help me? Thanks a lot.
You have to specify an object to call function inside new thread. Try this:
threads.emplace_back(std::thread(&MyClass::thread_task,this, i + 1));

why do i get "error C2678: binary '==' : no operator found which takes a left-hand operand of type"

I am using vs2012 and having the same problem. below is my sample source code.
#include "stdafx.h"
#include "iostream"
#include "list"
#include "algorithm"
#include "xutility"
using namespace std;
typedef struct Student{
string name;
int age;
int operator==(list<Student>::iterator itr)
{
return (!strcmp(itr->name.c_str(),this->name.c_str()));
}
}SStudent;
int _tmain(int argc, _TCHAR* argv[])
{
list<SStudent> myList;
SStudent temp1;
temp1.age = 10;
temp1.name = "aaaa";
myList.push_back(temp1);
list<SStudent>::iterator itr;
itr = std::find(myList.begin(), myList.end(), "aaaa");
return 0;
}
here is the error:
Error 1 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Student' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility 3186

can't get length of string in vc++

I want to retrive files with extension of .jpg from directory in vc++ 08. I'm not much comfortable with pointers so I got error when I try to get length of string in following code. Can anyone help me out??
Here is my code..
#include<iostream>
#include <string>
#pragma warning( disable : 4996 )
#include "dirent.h"
#pragma warning( default : 4996 )
using namespace std;
int main(int argc, char *argv[])
{
if(argc != 2)
{
cout<<"Usage: "<<argv[0]<<" <Directory name>"<<endl;
return -1;
}
DIR *dir;
dir = opendir (argv[1]);
if (dir != NULL)
{
string name; string ext = ".jpg"; int len;
cout<<"Directory Listing for "<<argv[1]<<" : "<<endl;
struct dirent *ent;
while ((ent = readdir (dir)) != NULL)
{
name = ent->d_name;
len = name.length; // here i got error...
name = name.substr(0, len-4);
if(_stricmp(name.c_str(), ext.c_str()) == 0)
{
cout<<ent->d_name<<endl;
}
else
{
cout<<"No JPG file"<<endl;
}
}
}
else
{
cout<<"Invalid Directory name"<<endl;
return -1;
}
return 0;
}
And error is
example.cpp(29) : error C3867: 'std::basic_string<_Elem,_Traits,_Ax>::length': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Ax>::length' to create a pointer to member
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1>\example.cpp(29) : error C2440: '=' : cannot convert from 'unsigned int (__thiscall std::basic_string<_Elem,_Traits,_Ax>::* )(void) const' to 'int'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1> There is no context in which this conversion is possible
Thanks in advance...
len = name.length();
// ^^
length is a member function, not a member variable. You need to call that function.

Resources