3

这可能是以前有人问过的问题,但我找不到...

我在文件中有一个类.hpp

class A{
    public:
        A(){//constructor}
        ~A(){//destructor}
        //some public methods and arguments

        template<typename Type>
            void func(Type t){//do something for numbers}

    private:
        //some private methods and arguments
}

模板方法应该适用于 int, double... 但不适用于字符串。因此,在我的.hpp文件中,我定义了func对数字的作用,并在我的.cpp文件中写道:

template<>
void A::func(std::string t){ // do something in that case}

但是当我将函数func与 一起使用时std::string,程序会调用数字的方法......所以我将.hpp文件替换为:

class A{
    public:
        A(){//constructor}
        ~A(){//destructor}
        //some public methods and arguments

        template<typename Type>
            void func(Type t){//do something for numbers}
        void func(std::string s);

    private:
        //some private methods and arguments
}

我的.cpp文件变成了:

void A::func(std::string t){ // do something in that case}

然后一切正常!

我的问题是,这是正确的方法吗?

4

2 回答 2

3

这不是部分特化(没有模板参数未特化),而是显式特化。

模板必须对使用它们的代码可见,如果您没有在头文件中声明特化,那么尝试A::func使用 a调用的代码string将实例化主模板(用于数字的模板)并使用它,因为它们没有t 知道 `string 特化甚至存在。

因此,您必须(至少)在标头中声明特化,以便它可以在.cpp文件之外使用:

template<>
void A::func(std::string t);

但是,您使用重载的替代方案更简单并且完全可以接受。它之所以起作用,是因为在标头中声明了重载string,因此调用它的代码知道要调用哪个函数。

于 2013-07-09T11:44:12.977 回答
0

重载对于许多目的来说是一种很好的方法。但是,我怀疑如果您也添加专业化,您的原始模板方法也可以工作const char *。这样,您可以传入字符串文字而不解析为数字版本。

于 2013-07-09T11:55:17.557 回答