2011-03-18 96 views
1

我有这样的问题: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); 
} 

+0

必须是一个错字:'INT(*比较器)()' – grep 2011-03-18 07:46:52

+0

整理这件事,请!当我试图编译它时,我得到了大约五个无关的错误。然后我放弃了。给我们一个代码块,我们可以通过ideone.com! – TonyK 2011-03-18 07:50:42

+0

@grep:我不明白 – cantrem 2011-03-18 07:50:59

回答

9

Tchar*const Tchar* const这是不一样的东西const char *。您需要:

Bubu<const char*> asd(strcmp); 

顶级常量为函数签名忽略,以便

int (*)(const char* const, const char* const); 

是同一类型

int (*)(const char*, const char*); 

所以你在额外的顶层常量虽然OK它不会让你得到任何简单的int (*comparer)(T t1, T t2);

+0

+1修复。我也推荐函数对象方法。 – Puppy 2011-03-18 07:51:59

+0

你是对的!因此我感到非常高兴。但是如果我想在模板中更改一些T,会发生什么?因为Bubu的类型有const关键字吗? – cantrem 2011-03-18 08:10:44

+0

@cantrem:你有很多选择。你可以编写一个包装函数来调用'strcmp',但是指向非''constst char'';你可以在你的类中使用字符类型而不是指针类型,并使用int(*)(const T *,const T *)';你可以使用一些特征风格的元函数来从'T = char *'中恢复'char'并从那里生成'const char *'。这实际上取决于你的模板应该提供什么样的灵活性以及它必须假设它的参数。 – 2011-03-18 08:20:58

0

不知道这是否是您的问题,但您的函数指针声明中的*位于错误的位置(至少与我见过的相比)。相反的:

int (comparer*)(const T t1, const T t2); 

它应该是:

int (*comparer)(const T t1, const T t2); 
+0

是的(至少现在,对不起,如果它是编辑前的错字) – cantrem 2011-03-18 08:11:59

3

如果T是专门为char*const T意味着char* const(即不可变的指针可变char),而不是const char* == char const*(即易变指向不可变的指针char)。

Bubu<const char*> asd(strcmp) 

将编译。

+0

是的,但事情是我需要那个可变的字符。任何想法如何保持我的布布声明,因为它是? – cantrem 2011-03-18 08:14:39

+0

把strcmp换成非const char *参数的函数太难看了! – cantrem 2011-03-18 08:19:03

0

我想这你想要做什么:

#include <cstring> 
#include <iostream> 

template<class T> 
class Bubu { 
public: 
    typedef int (*Comparator)(T, T); 

    Bubu(Comparator inComparator) : mComparator(inComparator) { } 

    int compare(T a, T b) 
    { 
     return mComparator(a, b); 
    } 

private: 
    Comparator mComparator; 
}; 

int main() 
{ 
    Bubu<const char*> obj(strcmp); 
    std::cout << obj.compare("one", "two") << std::endl; 
    return 0; 
} 
+0

感谢您的输入! – cantrem 2011-03-18 09:56:43