Khi tôi sử dụng một mẫu chuyên biệt trong các tệp đối tượng khác nhau, tôi gặp lỗi "nhiều định nghĩa" khi liên kết. Giải pháp duy nhất mà tôi tìm thấy liên quan đến việc sử dụng hàm "nội tuyến", nhưng có vẻ như đây chỉ là một số cách giải quyết. Làm cách nào để giải quyết vấn đề đó mà không sử dụng từ khoá "nội tuyến"? Nếu điều đó là không thể, tại sao?
Đây là mã ví dụ:
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
Cuối cùng:
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
Nếu tôi bỏ ghi chú "nội tuyến" bên trong hello.h, mã sẽ biên dịch và chạy, nhưng điều đó có vẻ giống như một loại "giải pháp" đối với tôi: điều gì sẽ xảy ra nếu hàm chuyên dụng lớn và được sử dụng nhiều lần? Tôi sẽ nhận được một nhị phân lớn? Có cách nào khác để thực hiện điều này không? Nếu có, làm thế nào? Nếu không, tại sao?
Tôi đã cố gắng tìm kiếm câu trả lời, nhưng tất cả những gì tôi nhận được là "sử dụng nội tuyến" mà không cần giải thích gì thêm.
Cảm ơn