【发布时间】:2011-05-25 15:27:23
【问题描述】:
当我在不同的目标文件中使用专用模板时,链接时出现“多重定义”错误。我找到的唯一解决方案是使用“内联”函数,但这似乎是一些解决方法。如何在不使用“inline”关键字的情况下解决这个问题?如果这不可能,为什么?
示例代码如下:
paulo@aeris:~/teste/cpp/redef$ cat hello.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
template <class T>
class Hello
{
public:
void print_hello(T var);
};
template <class T>
void Hello<T>::print_hello(T var)
{
std::cout << "Hello generic function " << var << "\n";
}
template <> //inline
void Hello<int>::print_hello(int var)
{
std::cout << "Hello specialized function " << var << "\n";
}
#endif
paulo@aeris:~/teste/cpp/redef$ cat other.h
#include <iostream>
void other_func();
paulo@aeris:~/teste/cpp/redef$ cat other.c
#include "other.h"
#include "hello.h"
void other_func()
{
Hello<char> hc;
Hello<int> hi;
hc.print_hello('a');
hi.print_hello(1);
}
paulo@aeris:~/teste/cpp/redef$ cat main.c
#include "hello.h"
#include "other.h"
int main()
{
Hello<char> hc;
Hello<int> hi;
hc.print_hello('a');
hi.print_hello(1);
other_func();
return 0;
}
paulo@aeris:~/teste/cpp/redef$ cat Makefile
all:
g++ -c other.c -o other.o -Wall -Wextra
g++ main.c other.o -o main -Wall -Wextra
最后:
paulo@aeris:~/teste/cpp/redef$ make
g++ -c other.c -o other.o -Wall -Wextra
g++ main.c other.o -o main -Wall -Wextra
other.o: In function `Hello<int>::print_hello(int)':
other.c:(.text+0x0): multiple definition of `Hello<int>::print_hello(int)'
/tmp/cc0dZS9l.o:main.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status
make: ** [all] Erro 1
如果我取消注释 hello.h 中的“内联”,代码将编译并运行,但这对我来说似乎是某种“解决方法”:如果专用函数很大并且多次使用怎么办?我会得到一个大的二进制文件吗?有没有其他方法可以做到这一点?如果是,如何?如果不是,为什么?
我试图寻找答案,但我得到的只是“使用内联”,没有任何进一步的解释。
谢谢
【问题讨论】:
-
将实际的专用实现放入.cpp而不是头文件