c ++如何将模板应用于模板类的子/朋友?

时间:2017-08-05 19:51:04

标签: c++ class oop templates inheritance

在c ++中,子类或朋友函数如何访问父类的所有可能模板类型?如何修改下面的代码,以便无论类型T是什么,友元函数和子函数都不会受到类型错误的影响? (目前只有int的类型正常工作)。

// 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;
}

3 个答案:

答案 0 :(得分:1)

这将允许friend函数访问所有派生类型的variable1。

//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;
};

答案 1 :(得分:1)

友元函数定义可以在类定义中:

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

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

该功能不是模板,因此允许升级/转换。

答案 2 :(得分: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
}