C++ 函子的部分模板特化';s调用传递给它的对象的成员方法
我有下面的函子和它的部分特化C++ 函子的部分模板特化';s调用传递给它的对象的成员方法,c++,templates,visual-c++,function-pointers,partial-specialization,C++,Templates,Visual C++,Function Pointers,Partial Specialization,我有下面的函子和它的部分特化 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
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;
};
我做错了什么?VisualC++中的const成员函数如何使函数模板工作? < p>您的<代码>操作程序()//>函数需要const(它们不会改变函数本身,但我不相信您需要一组新的函数)。
还请注意,标准为实现保留了所有以下划线和大写字母开头的类型。我认为
调用者中\T
的常量并不反映在中
MSVC中方法
的自动常量
(如果有的话,我觉得你提到的GCC的行为很奇怪)。
如果要在此
的常量中反映的常量,
如何准备辅助类选择\u 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;
....
模板
结构选择类型{typedef T Type;};
模板
结构选择类型{typedef Const_T Type;};
模板
结构调用程序
{
类型定义类型名称选择类型<
_T、 _Return(_T::*)(),_Return(_T::*)()const>::type方法;
....
感谢您在命名标准方面提出的观点-这只适用于类型名称吗?…感谢您的建议;现在尝试一下-不起作用。我现在修改了问题以更好地反映原始问题。(用两个代码片段测试了建议。)谢谢,这正是我要找的!
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));
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;
....