显式模板特化不能有存储类-成员方法特化

新手上路,请多包涵

假设我在 Visual Studio 中有以下代码

class foo
{
public:
    template<typename t>
    void foo_temp(int a , t s_)
    {
        std::cout << "This is general tmeplate method";
    }

    template<>
    static void foo_temp(int a , int s)
    {
        std::cout << "This is a specialized method";
    }
};

int main()
{
    foo f;
    f.foo_temp<std::string>(12,"string");
}

现在我试图将其转换为 GCC。通过关于 SO 的其他问题,我注意到如果类不是专门的,则在 GCC 成员方法中不能专门化。因此我想出了这个解决方案

class foo
{

    public:
    template<typename t>
    void foo_temp(int a , t s_)
    {
        std::cout << "This is general template method";
    }

};

template <>
/*static*/ void foo::foo_temp<int>(int a, int value) {
    std::cout << "Hello world";
}

现在这似乎可以解决问题,但是当我将 static 关键字包含到语句中时,我得到了错误

 explicit template specialization cannot have a storage class

现在 这个 线程谈论它,但我仍然对如何在这里应用它感到困惑。关于如何使最后一个方法成为静态的任何建议?另外我仍然对为什么模板化方法在 GCC 中不能是静态的感到困惑?

这是视觉工作室代码

class foo
{
public:
    template<typename t>
    void foo_temp(int a , t s_)
    {
        std::cout << "This is general tmeplate method";
    }

    template<>
    static void foo_temp(int a , int s)
    {
        std::cout << "This is a specialized method";
    }
};

int main()
{
    foo f;
    f.foo_temp<std::string>(12,"string");
}

原文由 James Franco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

关于如何使最后一个方法成为静态的任何建议?

你不能;语言不支持它。

此外,我仍然对为什么 GCC 中的模板化方法不能是静态的感到困惑?

他们能;它们不能既是静态的又是非静态的。例子:

 struct foo {
  template<typename T>
  void bar() {}

  template<typename T>
  static void baz() {}
};

int main() {
  foo f;
  f.template bar<void>();
  foo::baz<void>();
}

我很困惑为什么你必须有一个(非静态)模板成员函数的静态特化。我会认真地重新评估这段代码的完整性。

请注意,对于评论中的问题,不可能对静态成员函数进行模板特化,因为在这种情况下根本不可能对成员函数进行模板特化。 (改用重载。)

 struct foo {
  template<typename T, typename U>
  static void bar(T, U) {}

  // Error, you'd need to also specialize the class, which requires a template class, we don't have one.
  // template<>
  // static void bar(int, int) {}
  // test.cpp:2:12: error: explicit specialization of non-template ‘foo’
  //     2 | struct foo {
  //       |            ^

  // Partial specializations aren't allowed even in situations where full ones are
  // template<typename U>
  // static void bar<int, U>(int, U) {}
  // test.cpp:14:33: error: non-class, non-variable partial specialization ‘bar<int, U>’ is not allowed
  //   14 |   static void bar<int, U>(int, U) {}
  //      |                                 ^

  // Instead just overload
  template<typename U>
  static void bar(int, U) {}
};

原文由 OmnipotentEntity 发布,翻译遵循 CC BY-SA 4.0 许可协议

你尝试过老式的超载吗?根本不要将静态方法作为模板,让重载优先级负责挑选它。

原文由 Mark B 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题