C++ function pointers inside templates

霸气de小男生 提交于 2019-12-07 00:54:36

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);

Top level const is ignored for function signatures so

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

is the same type as

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

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);.

If T is specialized as char*, const T means char* const (i.e. immutable pointer to a mutable char), rather than const char* == char const* (i.e. mutable pointer to an immutable char).

Bubu<const char*> asd(strcmp)

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:

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

It should be:

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

I think this does what you want:

#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!