我正在尝试制作一个简单的程序,该程序将使用 for_each 和一个成员函数指针,以便根据元素的位置添加到 vector 中的每个元素(代码中的注释应该解释得足够好)。
但是,我遇到了一个错误,我不知道如何纠正我犯的错误(错误也在下面的评论中详细说明)。
如有任何帮助,我们将不胜感激。
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
}
最佳答案
您传入的函数指针因其参数类型不同而不同。
在下一行中,Add
函数接受一个参数。
void Add(const int &arg) {i_ += arg;}
但是 MemFuncPointer
没有参数:
MemFuncPointer(RetType (ClassType::*_pointer) ()) : pointer(_pointer) {}
这就是你遇到编译错误的原因。
要实现您的逻辑,您不能使用 for_each
,因为 for_each
不会将元素位置传递给仿函数。
你可以这样改正它:
修正类型错误。
MemFuncPointer(RetType (ClassType::*_pointer) ()) : pointer(_pointer) {} RetType operator() (ClassType &element) {return(element.*pointer) ();}
---->
MemFuncPointer(RetType (ClassType::*_pointer) (ArgType)) : pointer(_pointer) {} RetType operator() (ClassType &element, int i) {return(element.*pointer) (i);}
编写你的
for_each
版本:std::for_each(v.begin(), v.end(), func(&myClass::Add));
---->
for (int i = 0; i < v.size(); i++) { func(&myClass::Add)(v[i], i); }
但我仍然认为您不需要如此复杂的代码来完成这项工作。
关于c++ - "Cannot convert"成员函数指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17715099/