简体   繁体   中英

C++ - Invalid initialization of reference with template nested class

We have two templated classes, Class1 has a nested class. Class2 needs to be constructed / converted from that nested class object.

template<typename T> struct Class1{    
    Class1() = default;
    class Inner{};
};

template<typename T> struct Class2{
    Class2() = default;
    template<typename T2> Class2(const Class1<T2>&) {}
    template<typename T2> Class2(const typename Class1<T2>::Inner&) {}
};

void foo(const Class2<int>&){}

...

Class1<int> c1;
Class1<int>::Inner i1;

foo( c1);
foo( i1); // <===================ERROR

Error text is:

error: invalid initialization of reference of type ???const Class2<int>&??? from expression of type ???Class1<int>::Inner???

Why do I get this error? Constructing from Class1 works. Constructing from Inner if the classes are not templates also works.

There is no way for the second constructor (the one taking an Inner ) to ever be called. Since the template parameter T2 appears in a non-deduced context, to the left of a scope resolution operator that names a dependant type, it must be specified explicitly.

But template arguments of a templated constructor cannot be provided explicitly ! They must be deduced.

As such, substitution always fails for the second c'tor. Only the first c'tor ever makes it to overload resolution. And that overload resolution sees that you attempt to bind a Class2<int>::Inner object to a const Class2<int>& . That reference simply cannot bind.

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