gpt4 book ai didi

c++ - g++从具有模板参数的类派生

转载 作者:行者123 更新时间:2023-11-28 00:56:44 25 4
gpt4 key购买 nike

考虑以下代码:

template<class T>
class Base {
public:
void doSomething(){}
};

template<class T>
class Derived : public Base<T> {
public:
void doMore() {
doSomething(); //Affected line
}
};

在注释为“受影响的行”的行中,g++ (4.7) 说:

test.cc:11:16: error: there are no arguments to ‘doSomething’ that depend on a template parameter, so a declaration of ‘doSomething’ must be available [-fpermissive]

现在我想知道:

  • 如果模板参数 T 不存在,则不会发生此错误。有什么区别?
  • g++ 显然能够解决这个问题(如果我添加 -fpermissive,它可以正常编译)。我假设 g++ 试图为我作为“用户”(程序员)提供最佳体验。 g++ 不接受这段代码对我有什么好处?

谢谢!弥敦道

最佳答案

如果不加thisBase<T>你写的代码不符合标准——GCC 想阻止你这样做。另请参阅 GCC 4.7 的更改日志条目:

G++ now correctly implements the two-phase lookup rules such that an unqualified name used in a template must have an appropriate declaration found either in scope at the point of definition of the template or by argument-dependent lookup at the point of instantiation. As a result, code that relies on a second unqualified lookup at the point of instantiation to find functions declared after the template or in dependent bases will be rejected. The compiler will suggest ways to fix affected code, and using the -fpermissive compiler flag will allow the code to compile with a warning.

template <class T>
void f() { g(T()); } // error, g(int) not found by argument-dependent lookup
void g(int) { } // fix by moving this declaration before the declaration of f

template <class T>
struct A: T {
// error, B::g(B) not found by argument-dependent lookup
void f() { g(T()); } // fix by using this->g or A::g
};

struct B { void g(B); };

int main()
{
f<int>();
A<B>().f();
}

(在此处找到:http://gcc.gnu.org/gcc-4.7/changes.html)。

关于c++ - g++从具有模板参数的类派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798286/

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