gpt4 book ai didi

c++ - 调用传递给它的对象的成员方法的仿函数的部分模板特化

转载 作者:太空狗 更新时间:2023-10-29 21:50:10 26 4
gpt4 key购买 nike

我有以下仿函数及其偏特化

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com