gpt4 book ai didi

c++ - enable_if 继承的成员函数的名称查找错误

转载 作者:可可西里 更新时间:2023-11-01 18:36:32 25 4
gpt4 key购买 nike

我偶然发现了这个奇怪的名称查找问题,其中基类成员函数似乎根本不参与重载选择,即使它是使用 using 语句导入的。基类和派生类的成员函数都是带有 enable_if_t 的 SFINAE。

我能够使用以下代码重现我的问题:https://gcc.godbolt.org/z/ueQ-kY

#include <iostream>
#include <type_traits>

class MyTag {};

struct Base
{
template <typename RType>
std::enable_if_t<std::is_convertible<RType, int>::value> create(RType /*&&*/ ref)
{
std::cout << "Base::create(RType ref)" << std::endl;
}
};

struct Derived : Base
{
using Base::create;

template <typename Tag>
std::enable_if_t<std::is_same<Tag, MyTag>::value> create(Tag /*&&*/ tag)
{
std::cout << "Derived::create(Tag tag)" << std::endl;
}
};

int main()
{
Derived d;

d.create(MyTag());
d.create(0); // [x86-64 clang 7.0.0 #1] error: no matching member function for call to 'create'
}

虽然 GCC 在没有警告的情况下编译上述代码,但 clang、icc 和 MSVC 无法为 d.create(0); 的调用找到合适的重载并导致构建出错。事实上,从错误消息来看,Base::create 似乎甚至没有参与重载决议。

但是,当两个成员函数之一将其参数作为转发引用时,代码在所有主要编译器上都能正常编译。

最佳答案

Gcc 是错误的,应该拒绝你的例子。

using-declaration:
using using-declarator-list ;

[namespace.udecl]/1

Each using-declarator in a using-declaration introduces a set of declarations into the declarative region in which the using-declaration appears. The set of declarations introduced by the using-declarator is found by performing qualified name lookup ([basic.lookup.qual], [class.member.lookup]) for the name in the using-declarator, excluding functions that are hidden as described below.

排除的功能是:

[namespace.udecl]/15

When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list, cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting). Such hidden or overridden declarations are excluded from the set of declarations introduced by the using-declarator.


However, when one of the two member function takes its argument as a universal reference, the code compiles fine on all major compilers.

当其中一个函数将其参数作为(转发)引用时,此模板函数不再符合隐藏条件,因为它的parameter-type-list 不同。


OP 已经打开了一个错误报告,检查一下:
Bug 87478 - Hidden member function falsely takes part in qualified name lookup .

关于c++ - enable_if 继承的成员函数的名称查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52590220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com