【问题标题】:Multiple inheritance from instantiations of template class and what about access to member functions模板类实例的多重继承以及对成员函数的访问
【发布时间】:2015-06-28 20:59:44
【问题描述】:

我们看一下代码:

template <typename C>
class S {
public:
    void add (C c) { ++cnt; }
    size_t size () const { return cnt; }

private:
    size_t cnt {}; 
};

struct Foo1 {};
struct Foo2 {};
struct Foo3 {};

class Z : public S<Foo1>, public S<Foo2>, public S<Foo3> {
public:
    using S<Foo1>::add;
    using S<Foo2>::add;
    using S<Foo3>::add;

    using S<Foo1>::size;    // (1)
    using S<Foo2>::size;    // (2)
    using S<Foo3>::size;    // (3)
};

用法如下:

Z z;

z.add (Foo1 {});
z.add (Foo1 {});
z.add (Foo2 {});

cout << z.size () << endl;

这段代码在 gcc-5.1 (c++11) 下编译得很好,但这段代码在 clang-3.5 (c++11 - 抱歉,我没有更新版本的 clang) 下无法编译。

Clang 产生 "error: call to member function 'size' is ambiguous" 这基本上(从我的角度来看)是正确的,但 gcc 编译它并返回 2。

好的,但是这里更有趣,如果我切换标有 cmets (1) 和 (2) 的行的顺序,得到如下所示:

using S<Foo2>::size;    // (2)
using S<Foo1>::size;    // (1)

代码仍然在 gcc 上编译,结果是:1。

你可以想象,如果你在这两个之前写第(3)行,你会得到0。

所以,据我所见,gcc 首先使用 S::size 的声明,忽略其余部分并使用此声明。

谁能告诉我哪个编译器根据 C++ 标准做正确的工作?

报告于https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66698

最好, 阿图尔

【问题讨论】:

  • Wandbox link。好像是 4.6.4 的错误。
  • 显然,您的代码不明确,不应编译。 clang 报的错误是正确的。 MSVC 还报告无效的歧义。您应该报告错误。

标签: c++ c++11 gcc clang


【解决方案1】:

这是一个 gcc 错误。 Clang 和 MSVC 正确地标记了歧义。

如果你删除 3 个 using 语句,编译会因为歧义而失败(应该如此):

prog.cpp:39:12: error: request for member 'size' is ambiguous
  cout << z.size () << endl; return 0;
            ^
prog.cpp:9:12: note: candidates are: size_t S<C>::size() const [with C = Foo3; size_t = unsigned int]
     size_t size () const { cout<<typeid(C).name()<<endl; return cnt; }
            ^
prog.cpp:9:12: note:                 size_t S<C>::size() const [with C = Foo2; size_t = unsigned int]
prog.cpp:9:12: note:                 size_t S<C>::size() const [with C = Foo1; size_t = unsigned int]

根据标准成员查找算法,尽管使用声明,您应该得到相同的结果:

10.2/3: (...) 在声明集中,使用声明被它们指定的成员替换,类型声明(包括 injection-class-names) 被它们指定的类型替换。

我找不到与此错误完全匹配的内容。我建议你report it。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多