我在尝试编译一个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) 在Class.h:
class Class {
public:
template <typename T> void function(T value);
};
Run Code Online (Sandbox Code Playgroud)
在Class.cpp:
template<typename T> void Class::function(T value) {
// do sth
}
Run Code Online (Sandbox Code Playgroud)
在main.cpp:
#include "Class.h"
int main(int argc, char ** argv) {
Class a;
a.function(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个链接错误,因为Class.cpp从未实例化void Class::function<int>(T).您可以使用以下命令显式实例化模板类:
template class std::vector<int>;
Run Code Online (Sandbox Code Playgroud)
如何显式实例化非模板类的模板成员?
谢谢,
我正在使用boost property_tree加载一个ini文件.我的ini文件主要包含"简单"类型(即字符串,整数,双精度等),但我确实有一些表示数组的值.
[Example]
thestring = string
theint = 10
theintarray = 1,2,3,4,5
thestringarray = cat, dog, bird
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何通过编程方式加载theintarray并thestringarray进入容器对象,如vector或list.我注定要把它作为一个字符串读出并自己解析出来吗?
谢谢!