简体   繁体   中英

compiler can't deduce template parameters of nonmember operator+

I have the following code:

template<typename T>
class A{
public:
class B;
};

template<typename T>
class A<T>::B{
public:
template<typename Y>
friend typename A<Y>::B operator+(typename A<Y>::B& b,int num){
    return b;
}
};


int main(){
A<int>::B a;
A<int>::B b = operator+(a,1);    // gives an error: "no matching function for call to
                                //'operator+(A<int>::B&, int)'
A<int>::B b = operator+<int>(a,1); // works
return 0;
}

As mentioned in the title and the comments; why can't the compiler deduce the template parameters? It's important because I don't know how the person who will test it will use it.

By the way, if I define it as member function it works, but I still want to know why this way it doesn't. Plus if I define operator+(int,A<int>::B) it gives the same error (and obviously can't be member function).

The problems has nothing to do with operators or such: you cannot deduce template arguments for a class defining a nested type from the nested type. The trivial reason is that there is nothing which enforces that the nested type is uniquely nested in just one instantiation. You can call the operator explicitly specifying the non-deducable template argument(s), though.

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