【发布时间】:2011-07-15 06:03:25
【问题描述】:
考虑
struct C {
C() { printf("C::C()\n" ); }
C(int) { printf("C::C(int)\n" ); }
C( const C& ) { printf("copy-constructed\n"); }
};
还有一个模板函数
template< typename T > void foo(){
// default-construct a temporary variable of type T
// this is what the question is about.
T t1; // will be uninitialized for e.g. int, float, ...
T t2 = T(); // will call default constructor, then copy constructor... :(
T t3(); // deception: this is a local function declaration :(
}
int main(){
foo<int>();
foo<C >();
}
查看t1,当T为e.g.时,它不会被初始化。 int。另一方面,t2 将从一个默认构造的临时对象复制构造。
问题:除了 template-fu 之外,C++ 中是否可以默认构造一个泛型变量?
【问题讨论】:
-
对于那些认为...我以前见过这种问题的人,今天...他们是对的。但是这个问题的这个方面仍然没有答案。
-
@xtofl: template-fu 是什么?
-
@Nawaz:功夫的C++版本。
-
@Ben:酷。这个术语在 C++ 社区中足够流行吗?还是新发明的?
-
@Nawaz : [anything]-fu 很受欢迎。多见于“My python-fu is not strong enough”之类的句子中。
标签: c++ templates copy-constructor default-constructor