जब मैं विभिन्न ऑब्जेक्ट फ़ाइलों में एक विशेष टेम्पलेट का उपयोग करता हूं, तो लिंक करते समय मुझे "एकाधिक परिभाषा" त्रुटि मिलती है। एकमात्र समाधान जो मैंने पाया "इनलाइन" फ़ंक्शन का उपयोग करना शामिल है, लेकिन यह सिर्फ कुछ वर्कअराउंड की तरह लगता है। मैं "इनलाइन" कीवर्ड का उपयोग किए बिना कैसे हल कर सकता हूं? यदि यह संभव नहीं है, तो क्यों?
यहाँ उदाहरण कोड है:
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 के अंदर "इनलाइन" को अनसुना कर देता हूं, तो कोड संकलित और चला जाएगा, लेकिन यह सिर्फ मुझे किसी तरह का "वर्कअराउंड" लगता है: क्या होगा यदि विशेष फ़ंक्शन बड़ा है और कई बार उपयोग किया जाता है? क्या मुझे एक बड़ा बाइनरी मिलेगा? ऐसा करने के लिए कोई और रास्ता नहीं है? यदि हाँ, तो कैसे? यदि नहीं, तो क्यों?
मैंने उत्तरों की तलाश करने की कोशिश की, लेकिन मुझे जो भी मिला वह "बिना किसी स्पष्टीकरण के" इनलाइन का उपयोग करना था।
धन्यवाद