異なるオブジェクトファイルで特殊なテンプレートを使用すると、リンク時に「複数定義」エラーが発生します。私が見つけた唯一の解決策は、 "インライン"機能を使用することですが、ちょうどいくつかの回避策のように思えます。 「インライン」キーワードを使用せずにどのように解決できますか?それが不可能なら、なぜですか?異なるオブジェクトを使用する場合のテンプレート特殊化の複数定義
[email protected]:~/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
[email protected]:~/teste/cpp/redef$ cat other.h
#include <iostream>
void other_func();
[email protected]:~/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);
}
[email protected]:~/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;
}
:ここ
は、例えば、コードされ
最後に:
[email protected]:~/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内の「インライン」をコメント解除した場合は、コードをコンパイルして実行されますが、それはちょうど私には「回避策」のいくつかの種類のように思える:何特殊化された関数が大きくて何度も使用されていたら?大きなバイナリを入手できますか?これを行うための他の方法はありますか?はいの場合、どうですか?そうでない場合、なぜですか?
私は答えを探してみましたが、私が得たのはそれ以上の説明なしで「インラインで使う」ことでした。
おかげ
ヘッダーファイル – Anycorn