如何解决使用函数指针作为模板函数类型参数?
#include <iostream>
#include <unordered_map>
#include <utility>
#include <typeinfo>
using namespace std;
class Handle{
public:
int val;
bool getAskPrice(int& tmp) const
{
tmp = val;
return true;
}
bool setAskPrice(int& tmp)
{
val = tmp;
return true;
}
};
template<class RT,class ARG>
struct convertToAFL{
static RT to_afl(ARG);
};
template<class RT,class ARG>
struct convertFromAFL{
static RT from_afl(ARG);
};
template<>
struct convertToAFL<float,int>
{
static float to_afl(int& value)
{
return static_cast<float>(value);
}
};
template<>
struct convertFromAFL<int,float>
{
static int from_afl(float& val)
{
return static_cast<int>(val);
}
};
struct Getter{
template<typename TICK_D,bool (Handle::*Getter)(TICK_D&) const,typename AFL_D>
static AFL_D getter(const Handle& handle)
{
TICK_D temp;
bool exists;
exists = (handle.*Getter)(temp);
AFL_D x = convertToAFL<AFL_D,TICK_D>::to_afl(temp);
return exists ? x : -1;
}
};
struct Setter{
template<typename TICK_D,bool (Handle::*Setter)(TICK_D&),typename AFL_D>
static void setter(Handle& handle,AFL_D& val)
{
TICK_D x;
x = convertFromAFL<TICK_D,AFL_D>::from_afl(val);
(handle.*Setter)(x);
}
};
int main()
{
Handle h;
float val = 20.0;
Setter::setter<int,&Handle::setAskPrice,float>(h,val);
std::cout<<Getter::getter<int,&Handle::getAskPrice,float>(h);
//std::pair<,&Setter::setter<int,float>> x;
return 0;
}
上面的代码按预期工作,但是在main()
中而不是在调用函数时,如何存储指向模板化的Setter:setter()
和Getter::getter()
的指针?
我正在尝试类似
std::pair<&Setter::setter<int,float>,&Getter::getter<int,float>(h)> func_pair;
但是我说错了
main.cpp: In function ‘int main()’:
main.cpp:85:118: error: type/value mismatch at argument 1 in template parameter list for ‘template struct std::pair’
std::pair<&Setter::setter<int,float>(h)> func_pair;
^
main.cpp:85:118: note: expected a type,got ‘& setter’
main.cpp:85:118: error: template argument 2 is invalid
解决方法
静态成员函数只是普通函数。您可以像这样存储这些指针:
std::pair<void (*)(Handle& handle,float& val),float (*)(const Handle& handle)>
func_pair(&Setter::setter<int,&Handle::setAskPrice,float>,&Getter::getter<int,&Handle::getAskPrice,float>);
,
您可以使用decltype
来获取指针类型。
示例:
std::pair<int,decltype(&Setter::setter<int,float>)> x = {
1,&Setter::setter<int,float>
};
C ++ 11之前的版本:
std::pair<int,void(*)(Handle&,float&)> x(
1,float>
);
,
您的问题是模板参数是一种类型,但是您正在传递值(指针)作为参数。相反,您可以像这样使用auto
:
auto func_pair = std::make_pair(&Setter::setter<int,float>);
编辑:如果您使用的是C++03
,则std :: make_pair()仍然可用,但auto
不可用。您将需要使用一系列typedef
来手动描述类型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。