gpt4 book ai didi

c++ - "template"不需要关键字? [gcc/clang/Comeau 错误?]

转载 作者:可可西里 更新时间:2023-11-01 16:02:44 26 4
gpt4 key购买 nike

这是测试代码

template <class T> void f()
{
T t;
t.f<T>(0); //compiles even without the "template" keyword, what am I missing?
}

class abc
{
public:
template <typename T>
void f (int){}
};

int main()
{
f<abc>();
}

我正在使用 g++ 4.4.6。谢谢

P.S:我已经大大编辑了我的问题。请不要介意。

编辑:我向 EDG 的人问了这个问题,这是 Mike Herrick 不得不说的

We do diagnose this as an error in --strict mode as well as any mode that enables dependent name lookup (e.g., --dep_name, --parse_templates). Dependent name lookup is disabled in GNU emulation modes, so we don't emit this error in that case.

Dependent name processing requires that nonclass prototype instantiations be enabled (see below). As with nonclass prototype instantiations, enabling dependent name lookup is likely to cause compilation errors when compiling code that was not written with the feature in mind.

The dependent name lookup rules require that nondependent names be looked up at the point of use in the template definition, and that overload resolution be performed on nondependent calls at that point. For dependent calls, the set of names considered is the set visible at the point of use in the template definition plus any names made visible by argument-dependent lookup at the point of instantiation. Note that built-in types have no associated namespaces, so calls with only built-in types can only resolve to names visible in the template definition. Furthermore, names from dependent base classes are not visible to unqualified lookups.

下面说明了一些最常见的代码问题使用从属名称查找时:

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

template <class T> struct A : public B<T> {
X x; // error: X not visible yet (formerly an error in strict mode)
void g() {
f(); // error: B<T>::f not visible
this->f(); // must be written this way
h(1); // error: h(int) not visible using argument-dependent lookup
}
};
struct X {};
void h(int);
A<int> ai;

最佳答案

template关键字 都是必需的,因为 t是从属名称,因为 f<T>是依赖成员函数模板特化。相关规范分散在第 14 条中,但从 §14.2/4 开始(在 C++03 和 C++11 中)。

问题是由于不正确的名称查找:gcc 正在查找 namespace 作用域函数模板 f在声明点,然后在实例化点解析 f abc的成员函数模板.

如果您重命名命名空间作用域函数模板或成员函数模板,您将从编译器获得正确的行为。

这是一个长期存在的 gcc 错误:

Code with missing "template" keyword wrongly accepted

Weird clash with same names in different scopes

另请参阅针对这两个问题解决的许多重复错误。我没有看到为此打开的 Clang 错误。

函数模板中的名称查找在 C++03 中未指定;有许多关于该主题的缺陷报告,规范在 C++11 中进行了重大更改,以澄清细节和极端情况并修复细微问题。

关于c++ - "template"不需要关键字? [gcc/clang/Comeau 错误?],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986498/

26 4 0