मैं पहले से ही SFINAE मुहावरा काफी कुछ बार इस्तेमाल किया और मैं डाल करने के लिए इस्तेमाल किया गया मेरे टेम्पलेट मानकों में बजाय वापसी प्रकार में std::enable_if<>
। हालांकि, मैं कुछ मामूली मामले में आया जहां यह काम नहीं किया, और मुझे यकीन नहीं है कि क्यों। सबसे पहले, यहाँ है अपने मुख्य:SFINAE वापसी प्रकार में काम कर रहे हैं, लेकिन नहीं टेम्पलेट पैरामीटर के रूप में
template<typename T,
typename = typename std::enable_if<std::is_integral<T>::value>::type>
auto foo(T)
-> void
{
std::cout << "I'm an integer!\n";
}
template<typename T,
typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
auto foo(T)
-> void
{
std::cout << "I'm a floating point number!\n";
}
और यहाँ कोड का एक माना जाता है कि बराबर टुकड़ा है कि ठीक काम करता है है:
int main()
{
foo(5);
foo(3.4);
}
यहाँ foo
का कार्यान्वयन और त्रुटि से चलाता है
template<typename T>
auto foo(T)
-> typename std::enable_if<std::is_integral<T>::value>::type
{
std::cout << "I'm an integrer!\n";
}
template<typename T>
auto foo(T)
-> typename std::enable_if<std::is_floating_point<T>::value>::type
{
std::cout << "I'm a floating point number!\n";
}
मेरा प्रश्न है: क्यों, जबकि दूसरा एक यह ट्रिगर नहीं करता foo
के पहले कार्यान्वयन से चलाता है कि त्रुटि है?
main.cpp:14:6: error: redefinition of 'template<class T, class> void foo(T)' auto foo(T) ^ main.cpp:6:6: note: 'template<class T, class> void foo(T)' previously declared here auto foo(T) ^ main.cpp: In function 'int main()': main.cpp:23:12: error: no matching function for call to 'foo(double)' foo(3.4); ^ main.cpp:6:6: note: candidate: template<class T, class> void foo(T) auto foo(T) ^ main.cpp:6:6: note: template argument deduction/substitution failed: main.cpp:5:10: error: no type named 'type' in 'struct std::enable_if<false, void>' typename = typename std::enable_if<std::is_integral<T>::value>::type> ^
संपादित:
ठीक है। वास्तविक प्रदर्शन: [भाग संकलित करने में पहला असफल] (http://ideone.com/mJ8Zp6) और [2 सफलतापूर्वक संकलित भाग] (http://ideone.com/G0jBft)। –
अतिरिक्त जानकारी: वीएस 2012 नवंबर सीटीपी के साथ ही। –
[यह] (http://flamingdangerzone.com/cxx11/2012/06/01/almost-static-if.html) आप के लिए एकदम सही पढ़ा जाना चाहिए। – Xeo