gpt4 book ai didi

c++ - 强制编译器为模板类的所有成员函数生成代码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:19 24 4
gpt4 key购买 nike

假设我有这个程序

#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() )。

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

最佳答案

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

由于您隐式实例化了 A<int> ,只有你使用的函数被实例化:

[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; [..]

如果您显式实例化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

关于c++ - 强制编译器为模板类的所有成员函数生成代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com