gpt4 book ai didi

c++ - 这段代码在 C++ 中合法吗

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:12:31 25 4
gpt4 key购买 nike

我刚刚发现,当涉及到模板时,这段代码在 g++ 3.4.2 中编译并且可以工作,除非不调用 m():

template <typename T>
class C
{
T e;

public:
C(): e(0) {};

void m()
{
e = 0;
};
};

现在可以创建和使用实例了

C<const int> c;

c.m() 未被调用之前,没有编译错误,但这是合法的吗?

最佳答案

是的,这是合法的。模板规范是,在实例化方法之前,它不存在,因此编译器不会检查它。这是来自 the spec 的相关内容:

14.7.1 - Implicit instantiation

-9- An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation.

关于c++ - 这段代码在 C++ 中合法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1806022/

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