在单独的.cpp文件中专门化函数模板

Specializing function template in separate .cpp file

本文关键字:专门化 函数模板 文件 cpp 单独      更新时间:2023-10-16

我为一个非常简单的打印函数编写了一个模板,并将其放入一个自定义函数库中,这些函数都处理控制台IO。

我为一个特定的项目写了第二个库,它是原始库的子库。它专门针对其中一个模板。

我遇到了一个错误,(我怀疑)是由在声明专用模板之前对main.cpp进行的调用引起的。错误包含以下行:

 In instantiation of 'static void baseIO::print(S) [with s = std::vector<int>]'

这意味着它调用baseIO::print()而不是specialIO::print()

我尝试将specialIO::print()作为一个常规函数而不是模板,并在头中声明它为正常函数,但这拒绝了main.cpp对基本模板的访问。

有没有一种方法可以让我的专业化在main.cpp中可用,而不必声明在那里实现它?

//in main.cpp
#include <vector>
#include "specialIO.h"
main(){
    std::vector<int> myVector;
    specialIO::print(myVector);
    specialIO::print("hello world");
    return 1;
}

//in baseIO_templates.cpp - templates are outside of the baseIO.cpp file because of linker errors
template<typename S>     //primary template
void baseIO::print(S str){
    std::cout << str;
}
//baseIO.h
class baseIO{
public:
    template<typename S> //primary template
    static void print(S str);
}
#include "baseIO_templates.cpp"

//specialIO.cpp
template<>               //specialized template
void static specialIO::print(vector<int> myVector){
    for(int i : myVector){
        baseIO::print(i)
    }
}
//specialIO.h
class uberIO : public baseIO {
    //empty
}

调用代码时,所有模板代码都必须可供编译器使用。因此,如果您已经声明了template<T> void SomeFunction(T x);-那么当您用std::stringfloatMyStruct调用SomeFunction时,编译器将需要知道它的定义。因为如果编译器直到现在还不知道类型,它就无法找到正确的实现(或为正确的实现生成代码)。。。

因此,不能将模板实例化放在.cpp文件中——如果在头文件中声明,则可以将专门化放在.cpp文件中,因此:

class specialIO : public baseIO {
 public:
   template<>void static print<std::vector>(std::vector<int> v);
};

但如果你把它留空,编译器甚至不知道有这样一个打印函数,所以不能调用它——它会试图把std::vector传递到常规的baseIO::print<T>中,但这不会起作用,因为它无法做到这一点。