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)'
我不明白为什么。编译器不应该在那里看到“char*”而不是“T”吗?
编辑:Ideone.com 就绪代码:
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);
}
I have this problem:
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;
}
};
And in another file:
Bubu<char*> asd(strcmp);
Error:
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)'
I don't understand why. Shouldn't the compiler see a "char*" instead of "T" there?
EDIT: 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当
T
为char*
时,const T
为char* const
,这与不同>const char *
。您需要:函数签名会忽略顶级 const,因此
类型相同,
因此您可以使用额外的顶级 const,尽管它不会比更简单的
int (*comparer)(T t1 获得任何好处,T t2);
。When
T
ischar*
,const T
ischar* const
which isn't the same thing asconst char *
. You need:Top level const is ignored for function signatures so
is the same type as
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);
.如果
T
专门为char*
,则const T
表示char* const
(即指向可变const T
的不可变指针) code>char),而不是const char*
==char const*
(即指向不可变char
的可变指针)。将编译。
If
T
is specialized aschar*
,const T
meanschar* const
(i.e. immutable pointer to a mutablechar
), rather thanconst char*
==char const*
(i.e. mutable pointer to an immutablechar
).will compile.
不确定这是否是您的问题,但是函数指针声明中的
*
位于错误的位置(至少与我见过的相比)。而不是:应该是:
Not sure if this is your problem, but your
*
in your function pointer declaration is in the wrong place (at least compared to what I've ever seen). Instead of:It should be:
我认为这符合你的要求:
I think this does what you want: