2013-12-09 8 views
6

मैं फ़ंक्शन लिखने की कोशिश कर रहा हूं जो दो वैक्टरों के लिए स्केलर उत्पाद की गणना करता है। यहां कोड है और यह काम करता है।कई प्रकार के साथ रिकर्सिव टेम्पलेट फ़ंक्शन

template <int N> 
    int scalar_product (std::vector<int>::iterator a, 
         std::vector<int>::iterator b) { 
     return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1); 
    } 

    template <> 
    int scalar_product<0>(std::vector<int>::iterator a, 
          std::vector<int>::iterator b) { 
     return 0; 
    } 

लेकिन यहाँ समस्या है - मैं, टेम्पलेट प्रकार के साथ इस iterators बदलना चाहते हैं तो समारोह के हस्ताक्षर इस

template <typename Iterator ,int N> 
    int scalar_product (Iterator a, Iterator b) { 
     return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1); 
    } 

    template <typename Iterator> 
    int scalar_product<0>(Iterator a, 
          Iterator b) { 
     return 0; 
    } 

तरह ख़ाली दिखेगा लेकिन यह काम नहीं करता है - मैं संकलन मिल त्रुटि C2768: स्पष्ट टेम्पलेट तर्कों का अवैध उपयोग। यह मूर्खतापूर्ण प्रतीत होता है, लेकिन मुझे यह नहीं पता था कि इस त्रुटि से बचने के लिए मुझे क्या बदलना चाहिए।

+0

देखें इस: http://stackoverflow.com/questions/3716799/partial-specialization- ऑफ-फ़ंक्शन-टेम्पलेट्स – Nim

+0

['std :: inner_product'] (http://en.cppreference.com/w/cpp/algorithm/inner_product) का उपयोग क्यों न करें? लूप को आपके लिए इतना महत्वपूर्ण रूप से रेखांकित कर रहा है? – gwiazdorrr

+0

@Nim लिंक के लिए धन्यवाद - इससे मदद मिली। – htzfun

उत्तर

4

(AFAIK) वहाँ समारोह टेम्पलेट्स के आंशिक विशेषज्ञता के लिए कोई समर्थन नहीं है, इस कार्यक्षमता प्राप्त करने के लिए, आप इसे कुछ अलग ढंग से की तरह कुछ करने के लिए, की जरूरत है:

template <int N> 
struct scalar 
{ 
    template <typename Iterator> 
    static int product(Iterator a, Iterator b) 
    { (*a) * (*b) + scalar<N - 1>::product(a + 1, b + 1); } 
}; 

template <> 
struct scalar<0> 
{ 
    template <typename Iterator> 
    static int product(Iterator a, Iterator b) 
    { return 0; } 
}; 
5

असल में, आप का उपयोग करने की जरूरत नहीं प्रकार - मुझे उन्हें बहुत बोझिल लगता है और उनके अर्थशास्त्र अलग हैं। आप आंशिक रूप से एक समारोह के विशेषज्ञ नहीं कर सकते हैं, लेकिन आप उन्हें ओवरलोड और डिफ़ॉल्ट पैरामीटर अर्थ प्रदान करते हुए उन्हें विशेषज्ञताओं की तरह व्यवहार कर सकते हैं:

#include <type_traits> 

template <typename Iterator> 
int scalar_product(Iterator a, Iterator b, std::integral_constant<int, 0> = std::integral_constant<int, 0>() ) 
{ 
    return 0; 
} 

template <int N, typename Iterator> 
int scalar_product (Iterator a, Iterator b, std::integral_constant<int, N> = std::integral_constant<int, N>()) 
{ 
    return (*a) * (*b) + scalar_product(a + 1, b + 1, std::integral_constant<int, N-1>()); 
} 

int foo() 
{ 
    int a[] = { 1, 2, 3, 4 }; 
    int b[] = { 1, 1, 1, 1 }; 
    return scalar_product<4>(a, b); // returns 10 
} 
संबंधित मुद्दे