2017-08-05 74 views
2

在C++中,子類或朋友函數如何訪問所有可能的父類模板類型?我如何修改下面的代碼,以便無論類型T是什麼,朋友函數和子函數都不會遇到類型錯誤? (目前只有int的類型正常工作)。C++如何將模板應用於模板類的子/朋友?

// PARENT CLASS:¨ 

template <class T> 
class parent{ 
public: 
    T variable1; 

    friend int function1(parent, int a); 
}; 


//CHILD CLASS: 

class child : public parent<int> { 
public: 
    void setvariable(int a){ variable1 = a; }; 

}; 


// FRIEND FUNCTION: 

int function1(parent<int> k, int a) { 
    return k.variable1 +a; 
}; 

所以,下面再就沒有錯誤編譯:

int main() { 
    child child1;    //Child 
    child child2; 

    child1.setvariable(4); 
    child2.setvariable(4.4); //Type error/retyping 

    cout << function1(child1.variable1, 4) << endl;  // Function 
    cout << function1(child2.variable1, 4.0) << endl; // Type error 

    system("pause"); 
    return 1; 
} 
+0

的[聲明模板類的模板友元函數]可能的複製(https://stackoverflow.com/questions/18792565/declare-template-friend-function-of-template-class) – AndyG

+1

你能顯示的代碼示例你想擁有?例如,函數1的定義?對我而言,你不清楚你要求什麼。 – Jonas

+0

@Jonas函數的定義在第二行到最後一行;)。 – Tony

回答

1

這將允許友元函數爲所有派生類型訪問變量1。

//Parent 
template <class T> 
class parent{ 
public: 
    template<typename U> 
    friend U function1(parent<U>& parent, U a); 

private: 
    T variable1; 
}; 


//Child 
class child : public parent<int> { 
public: 
    void setvariable(int a){ variable1 = a; }; 
}; 


//Friend 
template<typename U> 
U function1(parent<U>& k, U a) { 
    return k.variable1 + a; 
}; 
+0

是的; )完美。 – Tony

0

我不完全相信你儘量做到什麼,但我認爲這可能是你想要的。

child類和function1現在是模板和function1第一個參數是一個參考。

實例化child對象時明確設置了模板參數。

#include <iostream> 
using namespace std; 
template <class T> 
class parent{ 
public: 
    T variable1; 

template <class U> 
    friend U function1(parent<U>&, U a); // now a template, using U to avoid shadowing 
}; 

//CHILD CLASS: 
template <class T> // now a template 
class child : public parent<T> { 
public: 
    void setvariable(T a){ this->variable1 = a; }; // using 'this' pointer because the function is a template now 
}; 

// FRIEND FUNCTION: 
template <class T> // now a template 
T function1(parent<T>& k, T a) { // first parameter is a reference, for polymorphism to work 
    return k.variable1 +a; 
}; 

int main() { 
    child<int> child1; // T = int 
    child<double> child2; // T = double 

    child1.setvariable(4); 
    child2.setvariable(4.4); 

    cout << function1(child1, 4) << endl; // first parameter is child1, and not the member variable 
    cout << function1(child2, 4.0) << endl; // first parameter is child2 
} 
+0

是的,這是針對該問題的一種特定解釋的解決方案。 :) –

1

朋友功能定義可以是內部類的定義:

template <class T> 
class parent{ 
public: 
    T variable1; 

    friend T function1(parent k, T a) { 
     return k.variable1 + a; 
    } 
}; 

這個功能是不是模板,以便允許推廣/轉換。

+0

非常有趣,我雖然在類聲明和外部編寫函數實現之間基本沒有區別。 – Tony

+0

它是爲每個模板定義它的唯一方式,而該函數本身就是模板。 – Jarod42