【问题标题】:class template instantiation类模板实例化
【发布时间】:2011-11-21 11:18:07
【问题描述】:

我刚刚阅读了关于 CRTP 的 wiki 文章,对模板实例化有点困惑。

根据维基,

成员函数体(定义)直到很长时间才被实例化 在他们的声明之后。

我不太明白这是什么意思。

假设我有一个类模板:

template <typename T>
class A
{
    public:
        void foo(T t)
        {
            //...
        };
};

当我实例化类模板A时,它是否实例化了成员函数foo()?

例如:

//in .cpp file
int main()
{
    A<int> a; //question 1
              //class template is instantiated here, isn't it? 
              //What about foo(), is it instantiated too?

    a.foo(10); //question 2
               //according to the quotation, foo() will not be instantiated until it is used.
               //if so, foo() is instantiated right here, not in question 1, right?
}

【问题讨论】:

标签: c++ templates instantiation


【解决方案1】:

你似乎混淆了一件事:

实例化发生在编译期间,而不是运行时。因此,您不能说“在哪一行”实例化了类模板或函数模板。

也就是说,成员函数模板没有与类模板一起实例化这一事实是正确的。

在这种情况下你可以观察到:你有以下文件

  • template.h(定义类 A 和函数 A::foo)
  • a.cpp(使用 A)
  • b.cpp(使用 A 和 A::foo)

然后在 a.cpp 的编译过程中,只有 A 会被实例化。但是,在编译 b.cpp 期间,两者都会被实例化。

因此,如果 A::foo 对于给定的一组模板参数包含一些语义上无效的代码,您将在 b.cpp 中得到编译错误,而不是在 a.cpp 中。

我希望这能解决问题!

【讨论】:

    【解决方案2】:

    对于类模板,经验法则是只实例化那些实际使用的成员。

    如果您想要完全实例化,C++ 提供显式实例化(但是,通常您不会;并非每一位都被完全实例化的事实意味着您的模板类更加通用,因为它降低了T 的要求,注意语法检查和非依赖类型的查找(不依赖于 T 的东西)仍然会发生。

    你会在这里找到更完整的答案:Template instantiation details of GCC and MS compilers

    【讨论】:

    • 支持提及显式实例化强制完成实例化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2016-10-11
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多