गैर-प्रकार पैरामीटर का उपयोग करके आपके वर्तमान इंटरफ़ेस के साथ यह संभव नहीं है।
आप के बजाय प्रकार पैरामीटर ले जा सकते हैं और एक std::integral_constant
में मानों लपेट:
template<class X, class Y, class Z>
class A { /* stuff */ };
// use as:
A<std::integral_constant<Color, Color::Red>,
std::integral_constant<ShowAxes, ShowAxes::True>,
std::integral_constant<ShowLabels, ShowLabels::True>> a;
इस बल्कि वर्बोज़ है, तो आप एक मैक्रो लिखने पर विचार कर सकता है:
#define AS_IC(Value) std::integral_constant<decltype(Value), Value>
और
के रूप में फिर से लिखने
A<AS_IC(Color::Red), AS_IC(ShowAxes::True), AS_IC(ShowLabels::True)> a;
वांछित प्रकार के मूल्य को 0 की सूची से निकालनारों सीधा है:
template<class Result, class...>
struct extract;
template<class Result, Result Value, class... Tail>
struct extract<Result, std::integral_constant<Result, Value>, Tail...> : std::integral_constant<Result, Value> {};
template<class Result, class Head, class... Tail>
struct extract<Result, Head, Tail...> : extract<Result, Tail...> {};
तो फिर तुम
// inside the definition of A
static constexpr Color col = extract<Color, X, Y, Z>::value;
Demo कर सकते हैं।
यह नहीं है, तथापि, एक ही कक्षा उत्पन्न है, लेकिन आप एक वर्ग टेम्पलेट A_impl
कि गैर प्रकार पैरामीटर के साथ अपने A
की तरह बर्ताव कर सकते हैं, और कहा कि वास्तविक क्रियान्वयन में शामिल है, और फिर A
एक उपनाम टेम्पलेट बनाने:
template< Color, ShowAxes, ShowLabels >
class A_impl
{/* stuff */};
template<class X, class Y, class Z>
using A = A_impl<extract<Color, X, Y, Z>::value,
extract<ShowAxes, X, Y, Z>::value,
extract<ShowLabels, X, Y, Z>::value>;
अब दिया
A<AS_IC(Color::Red), AS_IC(ShowAxes::True), AS_IC(ShowLabels::True)> a;
A<AS_IC(Color::Red), AS_IC(ShowLabels::True), AS_IC(ShowAxes::True)> b;
a
और b
एक ही प्रकार की है। Demo।
विकल्प में, आप भी decltype
और अधिक भार समारोह टेम्पलेट का उपयोग कर सकते हैं, लेकिन उस प्रकार के हर संभव आदेश के लिए एक समारोह टेम्पलेट घोषणा जोड़ने की आवश्यकता है:
template< Color c, ShowAxes a, ShowLabels l>
A<c,a,l> A_of();
template< ShowAxes a, ShowLabels l, Color c>
A<c,a,l> A_of();
// etc.
decltype(A_of<Color::Red, ShowAxes::True, ShowLabels::True>()) a1;
decltype(A_of<ShowAxes::True, ShowLabels::True, Color::Red>()) a2;
C++ वर्ग टेम्पलेट विशेषज्ञता? –
@ ब्रायन चेन आप विशेषज्ञता के साथ पैरामीटर के प्रकार नहीं बदल सकते –
मैं पैरामीटर के प्रकारों को बदलना नहीं चाहता हूं। विशेषज्ञता एक अच्छा विचार है, लेकिन मेरे पास 3 है! = 6 क्रमपरिवर्तन। इसके अलावा, मैं और पैरामीटर जोड़ने जा रहा हूँ। –