【发布时间】:2014-12-19 04:32:42
【问题描述】:
在下面的示例中,我假设类模板函数get_count() 将有两个不同的实例化,这是多余的,因为它们不依赖于模板参数。这是真的(或优化了吗?),当涉及到某些成员函数时,有没有办法让模板的所有实例化都使用一个通用函数(可能是一些模板参数通配符,如<*>?)?
template<class T>
class A {
private:
T obj;
int count;
public:
int get_count();
};
template<class T>
int A<T>::get_count() { // This function doesn't really need to
// depend on the template parameter.
return this->count;
}
int main() {
A<int> a; //<--First template instantiation
A<bool> b; //<--Second template instantiation
int i = a.get_count(); //<--Could theoretically use the same code
int j = b.get_count(); //<--
return 0;
}
另外,如果重新排列成员变量呢?
【问题讨论】:
标签: c++ class templates methods instantiation