强制编译器为模板类的所有成员函数生成代码? [英] Forcing the compiler to generate code for all member functions of a template class?

查看:91
本文介绍了强制编译器为模板类的所有成员函数生成代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个程序

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

int main() {
  A<int> a;
  a.foo();
  return 0;
}

g ++和clang ++都只为A<int>::foo()生成代码,而不为A<int>::bar()生成代码.当您要在调试时调用此函数时,这很烦人. (例如vector<T>::at()).

是否存在一些标记或其他方法,可以在每次实例化模板时强制所有成员函数生成代码?

解决方案

没有编译器标志,但是语言的规则支配着这里发生的事情,您可以利用它们来发挥自己的优势. /p>

由于您隐式实例化了A<int>,因此仅实例化了您使用的功能:

[C++11: 14.7.1/1]: [..] 类模板特化的隐式实例化导致类成员函数,成员类的声明而不是定义或默认参数的隐式实例化. ,作用域成员枚举,静态数据成员和成员模板; [..]

如果您明确地实例化A<int>,则整个实例都将被实例化.

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

template class A<int>;   // <----

int main() {
  A<int> a;
  a.foo();
}

以下是一些证明: http://coliru.stacked-crooked.com/a/582126aac45d6ea4

Say I have this program

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

int main() {
  A<int> a;
  a.foo();
  return 0;
}

Both g++ and clang++ only generate code for A<int>::foo(), but not for A<int>::bar(). This is annoying when you want to call this function while debugging. (e.g. vector<T>::at() ).

Is there some flag or other method by which you can force the generation of code for all member functions every time a template is instantiated?

解决方案

No compiler flags, but the rules of the language govern what is happening here, and you can use them to your advantage.

Since you are implicitly instantiating A<int>, only the functions you use are instantiated:

[C++11: 14.7.1/1]: [..] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates; [..]

If you explicitly instantiate A<int>, instead, then the whole thing gets instantiated.

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

template class A<int>;   // <----

int main() {
  A<int> a;
  a.foo();
}

Here is some proof: http://coliru.stacked-crooked.com/a/582126aac45d6ea4

这篇关于强制编译器为模板类的所有成员函数生成代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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