【问题标题】:Explicit instantiation of class template not instantiating constructor类模板的显式实例化不实例化构造函数
【发布时间】:2015-06-22 18:15:48
【问题描述】:

我正在使用 C++ 开发一个项目,但是当我显式实例化模板类时,我无法理解模板类的哪些成员会被显式实例化。我编写了以下文件,然后使用 Visual C++ 2008 Express Edition 的 Release 配置对其进行编译,然后弹出到反汇编程序中。

template<typename T> class test {
public:
    template<typename T> test(T param) {
        parameter = param;
    };
    ~test() {};
    int pop();
    int push();
    T parameter;
};

template<typename T> int test<T>::push() {return 1;}
template<typename T> int test<T>::pop() {return 2;}

template class test<int>;

int main() {
    return 0;
}

暂时忽略这个文件真的不需要模板,这编译得很好。我将 exe 放入反汇编程序,它告诉我 test::pop(void)、test::push(void) 和 test::~test(void) 是exe中的函数,但我没有看到构造函数。我知道我可以用

显式实例化构造函数
template test<int>::test(int);

这会导致 test::test(int) 与其他函数一起出现在反汇编中。我对显式实例化的理解是它应该告诉编译器为给定的一组参数实例化模板类的所有成员,那么为什么构造函数没有与所有其他成员函数一起显式实例化呢?

【问题讨论】:

  • 您的类模板无效,因为构造函数的模板参数隐藏了类的模板参数。但是 VC++ 编译器默默地接受它并不奇怪。
  • 如果模板参数未知,如何实例化构造函数?

标签: c++ templates constructor explicit-instantiation


【解决方案1】:

当构造函数是模板成员函数时,除非明确使用,否则不会实例化。

如果你将它设为非模板成员函数,你会看到构造函数的代码。

template<typename T> class test {
public:

    /***
    template<typename T> test(T param) {
        parameter = param;
    };
    ***/

    test(T param) : parameter(param) {}
    ~test() {}
    int pop();
    int push();
    T parameter;
};

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多