在讨论“隐藏功能”问题时,没有关于C++的爱吗?我想我应该提出这个问题。C++有哪些隐藏功能?
在讨论“隐藏功能”问题时,没有关于C++的爱吗?我想我应该提出这个问题。C++有哪些隐藏功能?
有很多"未定义行为"。通过阅读好书和标准,您可以学习如何避免它们。
大多数C++开发人员忽略了模板元编程的威力。请查看Loki Library。它广泛使用模板元编程实现了诸如类型列表、函数对象、单例模式、智能指针、对象工厂、访问者和多方法等多个高级工具(来自wikipedia)。在很大程度上,你可以将这些视为“隐藏”的C++特性。
map::insert(std::pair(key, value));
doesn't overwrite if key value already exists.
You can instantiate a class right after its definition: (I might add that this feature has given me hundreds of compilation errors because of the missing semicolon, and I've never ever seen anyone use this on classes)
class MyClass {public: /* code */} myClass;
请注意自由函数指针和成员函数指针初始化之间的区别:
成员函数:
struct S
{
void func(){};
};
int main(){
void (S::*pmf)()=&S::func;// & is mandatory
}
和自由函数:
void func(int){}
int main(){
void (*pf)(int)=func; // & is unnecessary it can be &func as well;
}
cout<<hex<<56; //otherwise you would have to write cout<<&hex<<56, not neat.
main()函数不需要返回值:
int main(){}
这是最短的有效C++程序。
template<class int>
class foo;
template
class foo<0> {
int* get<0>() { return array; }
int* array;
};
template<class int>
class foo<i> : public foo<i-1> {
int* get<i>() { return array + 1; }
};
我曾使用它生成一个类,其中包含10-15个函数,这些函数返回指向数组各个部分的指针,因为我使用的API需要每个值的一个函数指针。
即编程编译器通过递归生成一堆函数。简单易行。:)
假设您正在设计一个智能指针类。除了重载运算符*和->之外,智能指针类通常还定义了一个转换运算符以将其转换为bool类型:
template <class T>
class Ptr
{
public:
operator bool() const
{
return (rawptr ? true: false);
}
//..more stuff
private:
T * rawptr;
};
Ptr<int> ptr(new int);
if(ptr ) //calls operator bool()
cout<<"int value is: "<<*ptr <<endl;
else
cout<<"empty"<<endl;
if (shared_ptr<X> px = dynamic_pointer_cast<X>(py))
{
//we get here only of px isn't empty
}
Ptr <int> p1;
Ptr <double> p2;
//surprise #1
cout<<"p1 + p2 = "<< p1+p2 <<endl;
//prints 0, 1, or 2, although there isn't an overloaded operator+()
Ptr <File> pf;
Ptr <Query> pq; // Query and File are unrelated
//surprise #2
if(pf==pq) //compares bool values, not pointers!