2017-08-05 102 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