简体   繁体   中英

Friend funcitons of template classes

I want to return a nested class object using a friend function

template <typename T>
class X{
public:
    class Y{
    public:
        int y;
    }test;
public:
    X(){
        test.y=10;
    }

    template <typename U>
    friend Y fun(X<U>);
};


template <typename T>
X<T>::Y fun(X<T> x){
    return x.test;
}

But I get an error saying

need 'typename' before 'X::Y' because 'X' is a dependent scope

What is wrong?

You need to do literally what the error says: put typename before X<T>::Y :

template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}

Because the meaning of X<T>::Y is type-dependent on T , the compiler can't know in general whether X<T>::Y refers to a typename or a variable. In such circumstances the rule is that if you want it to be typename, you must say so explicitly with the typename keyword.

You have to write

template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}

becouse compliler can't resolve if Y is filed or type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM