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

Jam*_*nco 5 c++

假设我在 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");
}
Run Code Online (Sandbox Code Playgroud)

现在我试图将其转换为 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";
}
Run Code Online (Sandbox Code Playgroud)

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

 explicit template specialization cannot have a storage class
Run Code Online (Sandbox Code Playgroud)

现在这个线程谈论它,但我仍然对如何在这里应用它感到困惑。关于如何使最后一个方法静态的任何建议?另外我仍然对为什么模板化方法不能在 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");
}
Run Code Online (Sandbox Code Playgroud)

Omn*_*ity 5

\n

关于如何使最后一个方法静态化有什么建议吗?

\n
\n

你不能;该语言不支持它。

\n
\n

另外我仍然很困惑为什么模板化方法在 GCC 中不能是静态的?

\n
\n

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

\n
struct foo {\n  template<typename T>\n  void bar() {}\n\n  template<typename T>\n  static void baz() {}\n};\n\nint main() {\n  foo f;\n  f.template bar<void>();\n  foo::baz<void>();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我很困惑为什么必须对(非静态)模板成员函数进行静态专门化。我会认真地重新评估这段代码的合理性。

\n

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

\n
struct foo {\n  template<typename T, typename U>\n  static void bar(T, U) {}\n\n  // Error, you'd need to also specialize the class, which requires a template class, we don't have one.\n  // template<>\n  // static void bar(int, int) {}\n  // test.cpp:2:12: error: explicit specialization of non-template \xe2\x80\x98foo\xe2\x80\x99\n  //     2 | struct foo {\n  //       |            ^\n  \n  // Partial specializations aren't allowed even in situations where full ones are\n  // template<typename U>\n  // static void bar<int, U>(int, U) {}\n  // test.cpp:14:33: error: non-class, non-variable partial specialization \xe2\x80\x98bar<int, U>\xe2\x80\x99 is not allowed\n  //   14 |   static void bar<int, U>(int, U) {}\n  //      |                                 ^\n\n  // Instead just overload\n  template<typename U>\n  static void bar(int, U) {}\n};\n
Run Code Online (Sandbox Code Playgroud)\n