c++ - 为什么这个依赖名称查找找到的是全局标识符而不是方法?

标签 c++ templates c++11 gcc name-lookup

当编译器尝试解析i.template hi<T>();时它发现hi在全局命名空间中而不是方法 hii (ideone)。为什么?

#include <cstdio>

// Define 'hi' and 'bye' in the global namespace; these should *not* be used
template<typename T> struct hi { };
template<typename T> struct bye { };

// Foo needs to be templated for Foo::Inner to be a dependent type (I think)
template<typename T>
struct Foo
{
    struct Inner {
        // This is a plain-old templated member function of Inner, yes?
        template<typename U>
        void hi() { std::printf("hi!\n"); }

        // This is a plain-old member function of Inner
        void bye() { std::printf("bye!\n"); }
    };

    void sayStuff()
    {
        Inner i;
        i.template hi<T>();   // Fails to compile -- finds global hi instead of member
        i.bye();              // Compiles fine, finds member
    }
};

int main() {
    Foo<int> f;
    f.sayStuff();
    return 0;
}

我正在使用 g++ 4.9.1/4.9.2 ( -std=c++11 )。确切的错误消息:

prog.cpp: In member function 'void Foo<T>::sayStuff()':
prog.cpp:19:5: error: invalid use of 'struct hi<T>'
   i.template hi<T>();
     ^

此代码在 Clang 和 VS2013 中运行良好,但在 g++ 和 EDG 中生成错误。但哪些编译器是正确的?

除了更改成员(member)姓名之外,还有什么办法可以解决这个问题吗?在我的真实代码中,当 std 中的类型出现时,就会出现冲突。命名空间(例如通过 using namespace std 导入的)与我的成员函数之一具有相同的名称。显然,我希望我的实现代码是健壮的,并且不会导致用户代码中的随机名称冲突。

最佳答案

据我所知,这就是正在发生的事情。

DR228说:

[Voted into WP at April 2003 meeting.]

Consider the following example:

template<class T>
struct X {
   virtual void f();
};

template<class T>
struct Y {
  void g(X<T> *p) {
    p->template X<T>::f();
  }
};

This is an error because X is not a member template; 14.2 [temp.names] paragraph 5 says:

If a name prefixed by the keyword template is not the name of a member template, the program is ill-formed.

在某种程度上,这是完全有道理的:即使 p 具有依赖类型,但使用普通查找发现 X 是一个模板。然而,我认为这使得模板前缀的使用变得更加难以教授。

这是故意禁止的吗?

提议的决议(4/02):

删除 14.2 [temp.names] 第 5 段中第一次使用的“member”一词,使其第一句如下:

If a name prefixed by the keyword template is not the name of a template, the program is ill-formed.

但是,在最新公开的 C++ 标准草案 N4296 中§14.2.5 中出现以下措辞:

A name prefixed by the keyword template shall be a template-id or the name shall refer to a class template. [Note: The keyword template may not be applied to non-template members of class templates. —end note] [Note: As is the case with the typename prefix, the template prefix is allowed in cases where it is not strictly necessary; i.e., when the nested-name-specifier or the expression on the left of the -> or . is not dependent on a template-parameter, or the use does not appear in the scope of a template. —end note]

[Example:

template <class T> struct A {
  void f(int);
  template <class U> void f(U);
};

template <class T> void f(T t) {
  A<T> a;
  a.template f<>(t); // OK: calls template
  a.template f(t); // error: not a template-id
}

template <class T> struct B {
  template <class T2> struct C { };
};
// OK: T::template C names a class template:

template <class T, template <class X> class TT = T::template C> struct D { };
D<B<int> > db;

—end example]

这个措辞听起来很相似,但不同之处足以值得挖掘。我发现在N3126草案措辞已更改为此版本。

我能够将此更改链接回此 DR96 :

The following is the wording from 14.2 [temp.names] paragraphs 4 and 5 that discusses the use of the "template" keyword following . or -> and in qualified names.

{snip}

The whole point of this feature is to say that the "template" keyword is needed to indicate that a "<" begins a template parameter list in certain contexts. The constraints in paragraph 5 leave open to debate certain cases.

First, I think it should be made more clear that the template name must be followed by a template argument list when the "template" keyword is used in these contexts. If we don't make this clear, we would have to add several semantic clarifications instead. For example, if you say "p->template f()", and "f" is an overload set containing both templates and nontemplates: a) is this valid? b) are the nontemplates in the overload set ignored? If the user is forced to write "p->template f<>()" it is clear that this is valid, and it is equally clear that nontemplates in the overload set are ignored. As this feature was added purely to provide syntactic guidance, I think it is important that it otherwise have no semantic implications.

本质上,DR228 的细微变化在后续版本中丢失了;但是,由于没有设置类似的限制,除非标准中存在其他修订,否则 DR228 的意图可能仍然有效。这意味着在这种情况下,模板查找必须在全局范围内进行,即使它是依赖类型。

让我们看看我们的名称查找规则§3.4.5.1:

In a class member access expression (5.2.5), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list (14.2) or a less-than operator. The identifier is first looked up in the class of the object expression. If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template.

这似乎明确指出 baz.foo->template bar<T>();我们将首先查看类上下文,这包括标准模板查找。完成之后,如果没有找到任何内容,如果表达式的形式正确,我们就会跳转到整个表达式的上下文。本质上,它已经被提升,如果该行只是读取 template bar<T>(); ,则对该名称的查找必须以相同的方式执行。确实,我们已经从 DR228 中知道了这一点。我只是想仔细检查并确认。真正的问题是哪个模板应该获得优先级,全局范围内的模板还是类范围内的模板。

为此,我们现在需要询问非限定名称查找,因为现在 bar 与 foo 在同一上下文中被考虑,因此它不再遵循成员查找规则,而是遵循正常的非限定模板查找规则,这自然更喜欢本地版本。

总而言之,Clang 和 MSVC 似乎表现出了正确的行为,而 GCC 和 EDG 在这种情况下却没有表现出正确的行为。

我对 GCC 错误原因的最佳猜测是在触发规则后选择了错误的上下文分配给表达式。它可能只是偶然将其放置在全局级别,而不是将上下文放置在与后缀表达式相同的级别?也许它只是跳过第一个查找步骤? (但这只是猜测,我必须真正弄清楚在 GCC 源代码中查找的位置。)这也可以解释为什么 @Mikael Persson 将查找更改为合格的解决方案会导致编译重新开始。

来自提问者的链接错误报告让人们谈论为什么必须考虑全局范围,而且应该如此,但似乎很简单,本地范围匹配必须比全局范围匹配具有更高的优先级。最近那里似乎也有一些事件。

关于c++ - 为什么这个依赖名称查找找到的是全局标识符而不是方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930448/

相关文章:

C++11 整数初始化

c++ - std::vector 中止问题

c++ - 我们如何在子类中键入定义或重新定义模板化嵌套类?

c++ - 为什么这个boost::asio::tcp::socket可以重复使用?

c++ - SFINAE enable_if 显式构造函数

C++:是否可以将模板类的所有实例都加为好友?

c++ - 对 bool 的复合赋值安全吗?

C++11 正则表达式多行 : Why does the group ([^\\0]+\n)? some_text 在 match[1] 中包含所有内容?

c++ - 具有多态性的模板特化

C++模板类型和模板类型