के लिए सी ++ में टेम्पलेट विशेषज्ञता का एक मजबूत तरीका क्या है टेम्पलेट घोषणा और परिभाषा को अलग करने के लिए मध्यम आकार या यहां तक कि बड़ी जटिल परियोजनाओं में संकलन समय को कम करने के लिए उपयोगी उपयोगी है।पृथक हेडर/स्रोत
हालांकि, एक जटिल कोड में छोटे प्रोग्रामर गलतियों से अनजान व्यवहार परिवर्तन हो सकता है, उदा। एक विशेषज्ञता के बजाय एक सामान्य संस्करण कहा जाता है।
उदाहरण: मिस्ड घोषणा के कारण टेम्पलेट विशेषज्ञता अदृश्य हो गई।
///////////////////// file A.hpp /////////////////////
#include <iostream>
template <typename T>
class A
{
public:
void foo()
{
std::cerr << " calling generic foo " << std::endl ;
}
};
// forgetting following declaration leads to an unintended program behaviour
template <> void A<int>::foo();
///////////////////// file A-foo-int.cpp /////////////////////
#include "A.hpp"
template <>
void A<int>::foo()
{
std::cerr << "calling <int> version of foo" << std::endl;
}
///////////////////// file main.cpp /////////////////////
#include "A.hpp"
int main(int argc , char** argv)
{
A<int>* a = new A<int>();
a->foo();
return 0;
}
///////////////////// Makefile /////////////////////
CC = g++
CPPFLAGS += -Wall -O3
CXXFLAGS += --std=gnu++0x
all: nonrobust-template-setup
nonrobust-template-setup: main.o A-foo-int.o
$(CC) $(CPPFLAGS) main.o A-foo-int.o -o nonrobust-template-setup
clean:
rm -rf *.o nonrobust-template-setup
//////////////////////////////////////////
प्रश्न: एक और अधिक मजबूत सेटअप संभव (compiler- और मंच स्वतंत्र) और अगर, यह कैसे कैसा दिखेगा है?
यदि नहीं, तो परीक्षण करने के लिए एक अच्छा तरीका क्या है कि वांछित फ़ंक्शन संस्करण कहा जाता है?
मुझे लगता है कि आप सबकुछ कर रहे हैं जैसा आपको करना चाहिए। यह ठीक है कि यह C++ में कैसे काम करता है :) – cubuspl42