简体   繁体   English

C++ - 模板嵌套类的引用初始化无效

[英]C++ - Invalid initialization of reference with template nested class

We have two templated classes, Class1 has a nested class.我们有两个模板化类, Class1有一个嵌套类。 Class2 needs to be constructed / converted from that nested class object. Class2需要从该嵌套类对象构造/转换。

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.Class1构建作品。 Constructing from Inner if the classes are not templates also works.如果类不是模板,则从Inner构造也有效。

There is no way for the second constructor (the one taking an Inner ) to ever be called.无法调用第二个构造函数(采用Inner构造函数)。 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.由于模板参数T2出现在非推导的上下文中,在命名依赖类型的范围解析运算符的左侧,它必须明确指定。

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.因此,第二个 c'tor 的替换总是失败。 Only the first c'tor ever makes it to overload resolution.只有第一个 c'tor 使它重载决议。 And that overload resolution sees that you attempt to bind a Class2<int>::Inner object to a const Class2<int>& .并且该重载决议看到您尝试将Class2<int>::Inner对象绑定到const Class2<int>& That reference simply cannot bind.该引用根本无法绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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