c++ - 类模板的动态实例化被认为是显式的还是隐式的?

标签 c++ templates pointers explicit-instantiation

如果我有一个类模板并且我使用一个智能指针指向一个动态分配的专门实例的实例,这会导致整个类模板由编译器定义还是它也会等待一个成员函数被调用从指针实例化之前?

template <class T>
class Test {
    public:
        void nothing();
        void operation();

        static const int value;
};

template <class T>
const int Test<T>::value = 100;

template <class T>
void Test<T>::nothing() {
   /* invalid code */
   int n = 2.5f;
}

template <class T>
void Test<T>::operation() {
    double x = 2.5 * value;
}

int main() {
    std::unique_ptr<Test<int>> ptr = new Test<int>();  // mark1
    ptr->operation(); // mark2
    return 0;
}
  1. 是否在 mark1 处实例化了整个类模板?

  2. 如果不是,是否意味着此代码将正确编译并且成员函数 Test::nothing() 不会被实例化?

最佳答案

Does the entire class template get instantiated at mark1?

是的。类模板是隐式实例化的——只有类模板,而不是它的所有成员。

If not does that mean this code will compile correctly and the member function Test::nothing() not be instantiated?

not 并不意味着,如果没有使用 nothing(),它就不会被实例化。

关于c++ - 类模板的动态实例化被认为是显式的还是隐式的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821193/

相关文章:

c++ - 使用 g++ 4.8 时缺少 std::vector::erase() 的 const_iterator 重载

c++ - Qt:如何在 Mac 的应用程序菜单中添加自定义菜单项?

c++ - 是否可以使用索引迭代器访问另一个数组的索引?

c++ - 全特化模板类没有外线虚方法定义

c++ - 为指针分配空间

c++ - 在循环中取消分配内存

c - C语言十进制转二进制

c++ - Windows C++ 整数数组堆损坏

具有映射分配器问题的 C++ 模板

c++ - 编译时已知条件的标准 if/else?