異なるオブジェクトファイルで特殊なテンプレートを使用すると、リンク時に「複数定義」エラーが発生します。私が見つけた唯一の解決策は「インライン」関数を使用することですが、それはいくつかの回避策のようです。「インライン」キーワードを使用せずにそれを解決するにはどうすればよいですか?それが不可能な場合、なぜですか?
次にコード例を示します。
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内の「インライン」のコメントを外すと、コードはコンパイルされて実行されますが、それはある種の「回避策」のように思えます。専用の関数が大きく、何度も使用されている場合はどうなりますか?大きなバイナリを入手できますか?これを行う他の方法はありますか?はいの場合、どのように?そうでない場合、なぜですか?
答えを探してみましたが、何も説明せずに「インラインで使う」だけでした。
ありがとう