जब मैं विभिन्न ऑब्जेक्ट फ़ाइलों में एक विशेष टेम्पलेट का उपयोग करता हूं, तो मुझे लिंक करते समय "एकाधिक परिभाषा" त्रुटि मिलती है। मुझे मिला एकमात्र समाधान "इनलाइन" फ़ंक्शन का उपयोग करना शामिल है, लेकिन यह कुछ कामकाज की तरह लगता है। "इनलाइन" कीवर्ड का उपयोग किए बिना मैं इसे कैसे हल करूं? यदि यह संभव नहीं है, क्यों?टेम्पलेट विशेषज्ञता की एकाधिक परिभाषा
[email protected]ris:~/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 अंदर "इनलाइन" uncomment, कोड संकलन होगा और चलाने के लिए, लेकिन यह है कि सिर्फ मेरे लिए "वैकल्पिक हल" किसी तरह का की तरह लगता है: क्या यदि विशेष कार्य बड़ा है और कई बार उपयोग किया जाता है? क्या मुझे एक बड़ी बाइनरी मिल जाएगी? ऐसा करने के लिए कोई और रास्ता नहीं है? यदि हां, तो कैसे? यदि नहीं, क्यों?
मैंने जवाब देखने की कोशिश की, लेकिन मुझे जो भी मिला वह बिना किसी स्पष्टीकरण के "इनलाइन का उपयोग" था।
धन्यवाद
वास्तविक विशेष कार्यान्वयन को .cpp में डाल दिया गया है, फिर हेडर फ़ाइल – Anycorn