c++ - 类模板特化内部的静态成员函数

标签 c++ templates static instantiation specialization

我正在努力访问类模板中定义的静态成员函数。 在头文件 TemplateTest.h 中,我将主类 Template 定义为:

#include<iostream>

template<class T, class U>
struct TemplateTest
{
public:
    void static invoke();
    /*{

        std::cout << "Should not be called" << std::endl;

    }*/
};

然后源文件TemplateTester.cpp我放了一个特化:

#include "TemplateTest.h"

template<>
struct TemplateTest<int, bool>
{
    static void invoke()
    {
        std::cout << "invoke<int, bool>" << std::endl;   
    }
};

template struct TemplateTest<int, bool>; //instantiate to resolve linker issue

我明确地实例化了这个类,所以链接器可以正确解析。

在驱动程序 driver.cpp 中:

include "TemplateTest.h"

int main()
{
    TemplateTest<int, bool>::invoke();
    return 0;
}

当我用 g++ 编译 TemplateTest.cpp 时,它正确地生成了目标文件,但是当我尝试将它链接到驱动程序类时,它给出了我的链接器错误“对 `TemplateTest::invoke() 的 undefined reference ”

我浏览了其他相关帖子,例如 this one但我没有尝试访问函数模板。

非常感谢任何线索。

最佳答案

您是对的,您从 TemplateTester.cpp 创建的目标文件将包含您提供的特化符号。出现这种情况是因为任何显式特化都会导致模板被实例化,而且这种情况是双重的,因为您甚至添加了显式实例化(这实际上是不必要的)。

但是,在编译driver.cpp时,编译器并不知道特化,因为你只包含了TemplateTester.h,而特化是那里提到。所以编译器实例化模板,当然没有使用专门的定义,所以你遇到了问题。

标准说(我用斜体):

(§14.7.3/6) 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. If the program does not provide a definition for an explicit specialization and either the specialization is used in a way that would cause an implicit instantiation to take place or the member is a virtual member function, the program is ill-formed, no diagnostic required. An implicit instantiation is never generated for an explicit specialization that is declared but not defined. [...]

因此,当编译器处理 driver.cpp 时,您需要使编译器知道特化的声明和定义。执行此操作的最佳方法是将整个特化添加到 TemplateTester.h

再次注意,实际上不需要显式实例化。

关于c++ - 类模板特化内部的静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16910009/

相关文章:

c++ - cin 空间问题

c++ - 用于 std::array 的前向列表初始化的可变参数模板

c++ - 在C++中,如何获取Linux中服务的路径?

c++ - 使用 <charT> 比较单个字符

c++ - dllexport'ing 静态模板方法

c++ - 关于基类中的显式模板实例化和静态变量 : compiler bug or valid interpretation of the spec?

c++ - 为什么这两个模板函数的输出不同?

java - 为什么不能在方法内部创建非静态类的静态对象?

ios - 无法访问 iOS 静态库中资源包文件中的 Storyboard

c++ - 使用内联函数定义静态二维数组