是否为未使用的模板类方法生成了目标代码? [英] Is object code generated for unused template class methods?

查看:74
本文介绍了是否为未使用的模板类方法生成了目标代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++模板类,该类用3个不同的类型参数实例化。该类仅需要一种方法,而其他两种类型则永远不会调用该方法。

I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.

该方法的目标代码应为生成三次(针对实例化模板的所有类型),还是仅生成一次目标代码(针对其实际使用的类型)?

Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?

推荐答案

虚拟成员函数在实例化类模板时被实例化,但是非虚拟成员函数仅在被调用时被实例化。

Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called.

在C ++标准的[temp.inst]中涉及(在C ++ 11中,这是§14.7.1/ 10。在C ++ 14中,它是§14.7.1/ 11,在C ++ 17中是是§17.7.1/ 9。摘录自以下C ++ 17)

This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below)


实现不得隐式实例化函数模板,变量模板,成员
模板,非虚拟成员函数,成员类,类模板的静态数据成员,或 constexpr if语句(9.4.1),除非需要这样的实例化

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement (9.4.1), unless such instantiation is required

请注意,即使某些成员函数对于给定的模板参数而言不可实例化,也可以实例化类模板。例如:

Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example:

template <class T>
class Xyzzy
{
public:
    void CallFoo() { t.foo(); }  // Invoke T::foo()
    void CallBar() { t.bar(); }  // Invoke T::bar()

private:
    T t;
};

class FooBar
{
public:
    void foo() { ... }
    void bar() { ... }
};

class BarOnly
{
public:
    void bar() { ... }
};

int main(int argc, const char** argv)
{
    Xyzzy<FooBar>  foobar;    // Xyzzy<FooBar> is instantiated
    Xyzzy<BarOnly> baronly;   // Xyzzy<BarOnly> is instantiated

    foobar.CallFoo();         // Calls FooBar::foo()
    foobar.CallBar();         // Calls FooBar::bar()

    baronly.CallBar();        // Calls BarOnly::bar()

    return 0;
}

这是有效的,即使Xyzzy :: CallFoo()不可实例化,因为没有诸如BarOnly :: foo()这样的东西。此功能通常用作模板元编程工具。

This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool.

但是请注意,模板的实例化与生成多少目标代码没有直接关系。这取决于您的编译器/链接器的实现。

Note, however, that "instantiation" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.

这篇关于是否为未使用的模板类方法生成了目标代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆