gpt4 book ai didi

c++ - 成员函数实例化

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

以下在 GCC 4.8.1 上编译(使用 --std=c++11 ):

struct non_default_constructible { non_default_constructible() = delete; };

template<class T>
struct dummy {
T new_t() { return T(); }
};

int main(int argc, char** argv) {
dummy<non_default_constructible> d;
return 0;
}

棘手的部分是 dummy<non_default_constructible>::new_t()显然格式不正确,但这不会阻止编译器实例化 dummy<non_default_constructible> .

这是标准规定的行为吗?相关的部分/关键字是什么?

最佳答案

类模板的成员函数仅在上下文需要时才实例化,这意味着在尝试使用 new_t() 之前您不会看到任何错误。 . C++ 标准的相关部分是:

§ 14.7.1 Implicit instantiation [temp.inst]

  1. Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist. Unless a call is to a function template explicit specialization or to a member function of an explicitly specialized class template, a default argument for a function template or a member function of a class template is implicitly instantiated when the function is called in a context that requires the value of the default argument.

  2. [ Example:

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

    void h() {
    Z<int> a; // instantiation of class Z<int> required
    Z<char>* p; // instantiation of class Z<char> not required
    Z<double>* q; // instantiation of class Z<double> not required
    a.f(); // instantiation of Z<int>::f() required
    p->g(); // instantiation of class Z<char> required, and
    // instantiation of Z<char>::g() required
    }

    Nothing in this example requires class Z<double>, Z<int>::g(), or Z<char>::f() to be implicitly instantiated. — end example ]

关于c++ - 成员函数实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26123254/

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