簡體   English   中英

顯式模板專業化錯誤

[英]Explicit template specialization error

這應該很容易。 我正在使用模板,但出現編譯器錯誤。

#include <iostream>

template <class T1, class T2>
class Pair
{
    private:
        T1 a;
        T2 b;
    public:
        T1& first();
        T2& second();
        Pair(const T1& aval, const T2& bval) : a(aval), b(bval) {}
};

template <class T1, class T2>
T1& Pair<T1,T2>::first()
{
    return a;
}


template <class T1, class T2>
T2& Pair<T1,T2>::second()
{
    return b;
}

// Explicit Specialization
template <>
class Pair<double, int>
{
    private:
        double a;
        int b;
    public:
        double& first();
        int& second();
        Pair(const double& aval, const int& bval) : a(aval), b(bval) {}
};

template <>
double& Pair<double,int>::first()
{
    return a;
}

template <>
int& Pair<double,int>::second()
{
    return b;
}


int main(int argc, char const *argv[])
{

    Pair<int, int> pair(5,6);
    //Pair<double,int> pairSpec(43.2, 5);
    return 0;
}

錯誤看起來像這樣

main.cpp:42:27: error: no function template matches function template specialization 'first'
double& Pair<double,int>::first()
                          ^
main.cpp:49:24: error: no function template matches function template specialization 'second'
int& Pair<double,int>::second()

有什么線索可能會出錯嗎?

在方法聲明之前不需要模板<> 聲明。

double& Pair<double,int>::first() {
    return a;
}
int& Pair<double,int>::second() {
   return b;
}

應該夠了。

由於其他答案沒有解釋為什么這里不需要前綴template<> ,我將嘗試在我的答案中提供該解釋。

問題的解決方案

如下所述,我們只需要刪除template<>前綴,如下所示:

//no prefix template<> needed here
inline double& Pair<double,int>::first()
{
    return a;
}

//no prefix template<> needed here
inline int& Pair<double,int>::second()
{
    return b;
}

工作演示

請注意,添加了inline關鍵字,這樣我們就不會出現多重定義錯誤,因為通常我們在頭文件中實現模板,然后將這些模板包含在多個源文件中。

問題說明

我們不需要前綴template<>的原因是我們為完整類模板特化的成員函數提供了一個普通的類外定義 也就是說,我們實際上並沒有專門化成員函數,而是為這些成員函數提供了一個普通(非模板)的類定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM