- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下仿函数及其偏特化
template <class _T, typename _Return = void, typename _Arg = void>
struct Caller
{
typedef _Return(_T::*Method)(_Arg);
Caller(Method pm, _Arg a)
: _pMethod(pm),
_arg(a)
{}
_Return operator()(_T& obj)
{
return (obj.*_pMethod)(_arg);
}
Method _pMethod;
_Arg _arg;
};
template <class _T, typename _Return>
struct Caller<_T, _Return, void>
{
typedef _Return(_T::*Method)();
Caller(Method pm)
: _pMethod(pm)
{}
_Return operator()(_T& obj)
{
return (obj.*_pMethod)();
}
Method _pMethod;
};
我正在尝试按以下方式使用它:
struct Foo
{
void Bar() const
{
void(0);
}
};
// ...
std::list<Foo> foos;
const std::list<Foo> &rFoos(foos);
std::for_each(rFoos.begin(), rFoos.end(), Caller<const Foo>(&Foo::Bar));
我得到了最后一行代码(IDE 在调用者处获取):
error C2440: '' : cannot convert from 'void (__thiscall Foo::* )(void) const' to 'Caller<_T>' 1> with 1> [ 1> _T=const Foo 1> ] 1> No constructor could take the source type, or constructor overload resolution was ambiguous
此代码可在 g++ 环境中运行。 (如果我 Caller<Foo>(&Foo::Bar)
g++ 会提示,这是有道理的,因为该函数只会在 const 对象上调用)。
我尝试了各种方法,包括添加 operator()(const _T& obj)
/operator()(const _T& obj) const
变体到仿函数,但无济于事。
这将被编译器接受:
struct Foo
{
void Bar()
{
void(0);
}
};
// ...
std::list<Foo> foos;
const std::list<Foo> &rFoos(foos);
std::for_each(rFoos.begin(), rFoos.end(), Caller<Foo>(&Foo::Bar));
我做错了什么?如何使仿函数模板适用于 Visual C++ 中的 const 成员函数?
最佳答案
我认为 Caller
中 _T
的常量性没有反射(reflect)在 this
中MSVC 中 Method
的常量自动(如果有的话,我觉得你提到的GCC的行为很奇怪)。
如果想在this
的常量中体现_T
的常量,如何准备辅助类 Select_Type
如下所示,以及根据 T_
的常量选择合适的签名?
template <class C, class T, class Const_T>
struct Select_Type { typedef T type; };
template <class C, class T, class Const_T>
struct Select_Type<C const, T, Const_T> { typedef Const_T type; };
template <class _T, typename _Return>
struct Caller<_T, _Return, void>
{
typedef typename Select_Type<
_T, _Return(_T::*)(), _Return(_T::*)()const >::type Method;
....
关于c++ - 调用传递给它的对象的成员方法的仿函数的部分模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709056/
我是一名优秀的程序员,十分优秀!