[英]C++ template parameter inheritance
I have faced some code snippets that a class can inherited from another class via its template parameter.我遇到了一些代码片段,一个 class 可以通过它的模板参数从另一个 class 继承。 However, I do not understanding why I need to have the three using
line in struct D
.但是,我不明白为什么我需要在struct D
中使用三个using
行。 I try to call the say_hi()
function of d
but it states error: request for member 'say_hi' is ambiguous
and the error gone if I have the three using
lines.我尝试调用d
的say_hi()
function,但它指出error: request for member 'say_hi' is ambiguous
,如果我有三个using
行,错误就会消失。 Can anyone tell me why?谁能告诉我为什么?
struct C1 {
void say_hi(int) { puts("int hi"); }
};
struct C2 {
void say_hi(char) { puts("char hi"); }
};
struct C3 {
void say_hi(double) { puts("double hi"); }
};
template<typename T, typename U, typename V>
struct D : T, U, V {
using T::say_hi;
using U::say_hi;
using V::say_hi;
};
D<C1, C2, C3> d;
This is a variation on how the hiding rule works in c++: https://isocpp.org/wiki/faq/strange-inheritance#hiding-rule .这是隐藏规则如何在 c++ 中工作的变体: https://isocpp.org/wiki/faq/strange-inheritance#hiding-rule 。 But you actually dont declare any method in D which could overload the base class methods.但是您实际上没有在 D 中声明任何可能重载基本 class 方法的方法。 C++ compiler does not search for all possible overloads of your function call in whole inheritance tree but stop when it finds a correct overload (adhering to standard). C++ 编译器不会在整个 inheritance 树中搜索 function 调用的所有可能重载,而是在找到正确的重载(符合标准)时停止。 To modify this base working of compiler, you can add using
declarations to specify which overloads should be visible or to resolve ambiguities.要修改编译器的这种基本工作方式,您可以添加using
声明来指定哪些重载应该是可见的或解决歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.