c++ - 为什么模板类的显式方法特化可以在类内部没有其原型(prototype)声明的情况下工作

标签 c++ templates gcc

我正在使用以下简单示例

struct foo
{
    template <typename t>
    void funct(t a , t b)
    {
        std::cout << "Primary template called";
    }
};

template<>
void foo::funct<std::string> (std::string a , std::string b)
{
   std::cout << "Specialized";
}

上面的代码很好并且可以运行,但是我有点混淆在类外部声明的方法:

    template<>
    void foo::funct<std::string> (std::string a , std::string b)
    {
       std::cout << "Specialized";
    }

在类里面什至没有签名。我假设即使我将方法的签名添加到类中并使其看起来像这样,上面的代码也能正常工作,不幸的是这是错误的

struct foo
{
    template <typename t>
    void funct(t a , t b)
    {
        std::cout << "Primary template called";
    }

    template<>                                                 ---->Added Extra
    void funct<std::string> (std::string a , std::string b);   ----->Added Extra
};

 template<>
    void foo::funct<std::string> (std::string a , std::string b)
    {
       std::cout << "Specialized";
    }

我的问题是为什么它会这样?类/结构外的方法假定存在一个带有签名的方法

  funct(std::string a , std::string b);

但没有。如果有人能解释这种行为,我将不胜感激。

最佳答案

显式特化会导致隐式实例化,无需在此显式声明。

14.7.3$6 显式特化 [temp.expl.spec]

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

并且,不能在类范围内声明显式特化。

14.7.3$2 显式特化 [temp.expl.spec]

An explicit specialization shall be declared in a namespace enclosing the specialized template.

因此,如果您愿意,可以在类范围之外显式添加显式特化声明,即使在这里没有多大意义。

template<>
void foo::funct<std::string> (std::string a , std::string b);

LIVE

关于c++ - 为什么模板类的显式方法特化可以在类内部没有其原型(prototype)声明的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32973787/

相关文章:

c++ - 如何在 C++ 中的 switch 中使用 bool 表达式

c++ - 为什么两个函数有相同的地址?

c++ - 为模板特化提供*隐式*转换运算符

复制 glibc 库

c++ - QTcpSocket - 扩展 QRunnable 时指定了无效句柄

c++ - 定义可变大小的元组

c++ - 如何在编译时测试模板函数是否存在

c++ - 实例化重载函数模板

c++ - 链接器错误;找不到结构中的静态变量

gcc - 如何通过 gcc 的确切名称链接库?