C ++模板陷阱 [英] C++ template gotchas
问题描述
刚刚我不得不通过网站找出为什么模板类模板成员函数给出语法错误:
just now I had to dig through the website to find out why template class template member function was giving syntax errors:
template<class C> class F00 {
template<typename T> bar();
};
...
Foo<C> f;
f.bar<T>(); // syntax error here
现在我意识到模板括号被当作关系运算符。为了做到目的,需要以下奇怪的语法,cf http://stackoverflow.com/questions/1682844/templates-template-function-not-playing-well-with-classs-template-member-functi :
f.template bar<T>();
你遇到的C ++ / C ++模板的其他奇怪的方面和秘诀考虑是常识?
what other bizarre aspects and gotcha of C++/C++ templates you have encountered that were not something that you would consider to be common knowledge?
推荐答案
我第一次从另一个模板类继承一个模板类, p>
I got tripped up the first time I inherited a templated class from another templated class:
template<typename T>
class Base {
int a;
};
template<typename T>
class Derived : public Base<T> {
void func() {
a++; // error! 'a' has not been declared
}
};
问题是编译器不知道 Base< T&
将成为默认模板或专用模板。专用版本可能不具有 int a
作为成员,因此编译器不会假定它可用。但你可以告诉编译器它将在那里与使用
指令:
The problem is that the compiler doesn't know if Base<T>
is going to be the default template or a specialized one. A specialized version may not have int a
as a member, so the compiler doesn't assume that it's available. But you can tell the compiler that it's going to be there with the using
directive:
template<typename T>
class Derived : public Base<T> {
using Base<T>::a;
void func() {
a++; // OK!
}
};
或者,您可以明确表示您正在使用 T
:
Alternatively, you can make it explicit that you are using a member of T
:
void func {
T::a++; // OK!
}
这篇关于C ++模板陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!