0
for_each 및 멤버 함수 포인터를 사용하여 요소 위치에 따라 벡터의 각 요소를 추가하는 간단한 프로그램을 만들려고합니다. 코드는 충분히 설명해야합니다)."Can not convert"멤버 함수 포인터와 함께 문제
그러나 단일 오류로 실행 중이며 내가 작성한 오류를 수정하는 방법을 알 수 없습니다 (오류는 아래 주석에도 자세히 설명되어 있습니다).
도움을 주시면 감사하겠습니다. 감사합니다.
MAIN.CPP
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
class myClass
{
public:
myClass() : i_(0) {}
myClass(int i) : i_(i) {}
const int& Get() const {return i_;}
void Add(const int &arg) {i_ += arg;}
private:
int i_;
};
template <typename RetType, typename ClassType, typename ArgType>
class MemFuncPointer
{
public:
MemFuncPointer(RetType (ClassType::*_pointer)()) : pointer(_pointer) {}
RetType operator() (ClassType &element) {return(element.*pointer)();}
private:
RetType (ClassType::*pointer) (ArgType);
};
template <typename RetType, typename ClassType, typename ArgType>
MemFuncPointer<RetType, ClassType, ArgType> func(RetType (ClassType::*pointer) (ArgType))
{
return MemFuncPointer<RetType, ClassType, ArgType>(pointer);
// The above line gets...
// error C2440: '<function-style-cast>' : cannot convert from
// 'void (__thiscall myClass::*) (const int &)' to
// 'Functor<RetType,ClassType,ArgType>'
}
int main(void)
{
// Create Vector v
std::vector<myClass> v;
// Push back ten 10's
for(int i = 0; i < 10; ++i)
v.push_back(myClass(10));
// Set two iterators
std::vector<myClass>::const_iterator it = v.begin(), it_end = v.end();
// Print the vector and newline
for(; it != it_end; ++it)
std::cout << it->Get() << " ";
std::cout << "\n";
// for_each
std::for_each(v.begin(), v.end(), func(&myClass::Add));
// Print the vector and newline
for(it=v.begin(); it!=it_end; ++it)
std::cout << it->Get() << " ";
std::cout << "\n";
// Final vector should be
10, 11, 12, 13, 14, 15, 16, 17, 18, 19
}
'std :: for_each'는이 경우에 'myClass'를 취하는 단항 펑터를 필요로합니다. 멤버 함수는 'this'에 대해 암시적인 첫 번째 매개 변수를 취하므로 단항 함수가 아닙니다. myClass 인스턴스를 바인딩하거나 ['std :: mem_fn'] (http://en.cppreference.com/w/cpp/utility/functional/mem_fn)을 사용해야합니다. 그러나'myClass :: Add'는'int'를 기대하며'myClass'를 전달할 것입니다. 'myClass'를 취하는'Add' 메소드가 필요합니다. – juanchopanza
'std :: function'을 사용할 수 있다면 custom-wrapping 함수 포인터는 필요하지 않습니다. –