मैं एक टेम्पलेट वर्ग (प्राप्त < नामित> यहाँ) को लागू करने की कोशिश कर रहा हूँ कि एक संरचना एच दिया, प्रकार Get<H>::type
H
ही अगर qualified-id
H::der
मौजूद नहीं है, और Get<H::der>::type
अन्यथा है । मैं समझ नहीं पा रहा हूं कि निम्नलिखित कोड में क्या गड़बड़ है:C++ पुनरावर्ती प्रकार लक्षण
#include <iostream>
#include <typeinfo>
using namespace std;
template<class U, class V = void>
struct Get
{
static const char id = 'A';
typedef U type;
};
template<class U>
struct Get<U,typename U::der>
{
static const char id = 'B';
typedef typename Get<typename U::der>::type type;
};
struct H1
{ };
struct H2
{ typedef double der; };
struct H3
{ typedef void der; };
struct H4
{ typedef H2 der; };
void print(char id, const char* name)
{
cout << id << ", " << name << endl;
}
int main(int , char *[])
{
print(Get<H1>::id, typeid(Get<H1>::type).name()); // prints "A, 2H1", OK
print(Get<H2>::id, typeid(Get<H2>::type).name()); // prints "A, 2H2", why?
print(Get<H3>::id, typeid(Get<H3>::type).name()); // prints "B, v" , OK
print(Get<H4>::id, typeid(Get<H4>::type).name()); // prints "A, 2H4", why?
}
मुझे इस कोड को अपेक्षित व्यवहार करने में कुछ मदद चाहिए। विशेष रूप से, मैं चाहता हूँ कि < एच 2 प्राप्त करें> :: प्रकार बराबर डबल करने के लिए लिए किया गया था, और एक ही < एच 4 प्राप्त करें> :: प्रकार।
संभव डुप्लिकेट http://stackoverflow.com/questions/3008571/template-specialization-to-use -default-type-if-class-member-typedef-does-not-exi) –
इस उत्तर में litb की 'tovoid' चाल आपकी समस्या हल करती है: http://stackoverflow.com/a/3009891/245265 –
अच्छी चाल, हेवन यह नहीं जानता था। – ipc