相关疑难解决方法(0)

为什么模板只能在头文件中实现?

引自C++标准库:教程和手册:

目前使用模板的唯一可移植方法是使用内联函数在头文件中实现它们.

为什么是这样?

(澄清:头文件不是唯一的便携式解决方案.但它们是最方便的便携式解决方案.)

c++ templates c++-faq

1660
推荐指数
14
解决办法
46万
查看次数

将模板化的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万
查看次数

模板成员函数的实例化

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)

如何显式实例化非模板类的模板成员?

谢谢,

c++ templates

35
推荐指数
2
解决办法
3万
查看次数

Boost property_tree - 使用简单的数组或容器

我正在使用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)

我无法弄清楚如何通过编程方式加载theintarraythestringarray进入容器对象,如vectorlist.我注定要把它作为一个字符串读出并自己解析出来吗?

谢谢!

c++ boost

3
推荐指数
1
解决办法
2949
查看次数

标签 统计

c++ ×4

templates ×3

boost ×1

c++-faq ×1

class ×1

header ×1

linker ×1