相关疑难解决方法(0)

将模板化的C++类拆分为.hpp/.cpp文件 - 是否可能?

我在尝试编译一个C++模板类时遇到错误,该类在一个.hpp.cpp文件之间分开:

$ g++ -c -o main.o main.cpp  
$ g++ -c -o stack.o stack.cpp   
$ g++ -o main main.o stack.o  
main.o: In function `main':  
main.cpp:(.text+0xe): undefined reference to 'stack<int>::stack()'  
main.cpp:(.text+0x1c): undefined reference to 'stack<int>::~stack()'  
collect2: ld returned 1 exit status  
make: *** [program] Error 1  
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

stack.hpp:

#ifndef _STACK_HPP
#define _STACK_HPP

template <typename Type>
class stack {
    public:
            stack();
            ~stack();
};
#endif
Run Code Online (Sandbox Code Playgroud)

stack.cpp:

#include <iostream>
#include "stack.hpp"

template <typename Type> stack<Type>::stack() {
        std::cerr << "Hello, …
Run Code Online (Sandbox Code Playgroud)

c++ linker templates header class

89
推荐指数
4
解决办法
9万
查看次数

标签 统计

c++ ×1

class ×1

header ×1

linker ×1

templates ×1