从类模板的(部分)专门化调用静态函数



有没有办法让这些代码按预期工作?

#include <iostream>
using namespace std;
template<typename T> class templated{
public:
    static void f(){
        cout<<"doing something generically"<<endl;
    }
};
template<> class templated<int>{
public:
    static void g(){
        cout<<"doing something else, but specific to int"<<endl;
        f();
    }
};
int main(){
    templated<int>::g();
}

G++抱怨f没有在作用域中声明。我已经尝试了调用f()的所有可能的变体(templated<int>::f(),在templated中放置一个伪声明,将声明移到类定义之外…),所有这些都失败了,所以我在这里省略它们。

在这种特殊情况下,您可以继承,因为您没有使用模板参数类型:

template<> class templated<int>: templated<void>{
public:
    static void g(){
        cout<<"doing something else, but specific to int"<<endl;
        f();
    }
};

不,专业化与基本模板完全分离,不会从中"继承"任何东西。

也许你可以添加一个可以从任何地方调用的免费函数?

您的专用版本根本没有f()(这里没有"继承")。

如果您想要继承,您可能应该考虑将f()移动到基类中。

您可以使用某种包装器,比如

    template<typename T>
    class templated_core
    {
      public:
        static void f()
        {
          cout<<"doing something generically"<<endl;
        }
    };
    template<typename T>
    class templated : public templated_core<T>
    {
    };
    template<>
    class templated<int> : public templated_core<int>
    {
      public:
        static void g()
        {
          cout<<"doing something else, but specific to int"<<endl;
          f();
        }
    };

最新更新