模板中的C ++函数指针 [英] C++ function pointers inside templates
本文介绍了模板中的C ++函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个问题:
template<typename T> class Bubu
{
...
int (*comparer)(const T t1, const T t2);
...
public:
Bubu(int (*_comparer)(const T t1, const T t2))
{
comparer = _comparer;
}
};
在另一个文件中:
Bubu<char*> asd(strcmp);
错误:
error C2664: 'Bubu<T>::Bubu(int (__cdecl *)(const T,const T))' :
cannot convert parameter 1 from 'int (__cdecl *)(const char *,
const char *)' to 'int (__cdecl *)(const T,const T)'
我不明白为什么.
支持Ideone.com的代码:
the Ideone.com-ready code:
int asdf(const char* a, const char* b)
{ return 0; }
template class Bubu
{
int (*comparer)(const T t1, const T t2);
public:
Bubu(int (*_comparer)(const T t1, const T t2))
{
comparer = _comparer;
}
};
int main(int argc, char* argv[])
{
Bubu asd(asdf);
}
推荐答案
当T
为char*
时,const T
为char* const
,与const char *
不同.您需要:
When T
is char*
, const T
is char* const
which isn't the same thing as const char *
. You need:
Bubu<const char*> asd(strcmp);
对于函数签名,顶层const被忽略
Top level const is ignored for function signatures so
int (*)( const char* const, const char* const );
与
int (*)( const char*, const char* );
尽管在简单的int (*comparer)(T t1, T t2);
上并不能给您带来任何好处,但是您可以在顶级顶级常量上使用.
so you're OK on the extra top level const although it doesn't gain you anything over the simpler int (*comparer)(T t1, T t2);
.
这篇关于模板中的C ++函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文