Effective Modern C++:alias,enum,override
Alias is preferred to typedef
It is clearer:
typedef void (*FP)(int, const std::string&); // old way: typedef
using FP = void (*)(int, const std::string&); // new way: alias
It support template:
template<typename T>
using MyAllocList = std::list<T, MyAlloc<T>>;
enum is preferred to be scoped
Comparison between the old and new way:
enum Color { black, white, red };
enum class Color { black, white, red };
Using the old way, the enums are all globally active,then:
auto white = false
will be wrong, because the word white is already defined. When using the new method, Color::white will be used instead, so white is now free to use.
We can also call it “enum class”.
Attention: scoped enum can not be converted to int implicitly! Color::white is not equal to 1, it is just Color::white. But you can define a enum’s underlying type:
enum Color: short {black=0,white=1,red=2};
Forward declaration is supported:
enum class Color;
override should be added when overriding
class Base
{
public:
Base() {};
~Base() {};
virtual void func()
{
cout << "I am base class\n";
};
};
class Derived : public Base
{
public:
Derived() {};
~Derived() {};
void func() override
{
Base::func();
cout << "I am derived class\n";
};
};
void main()
{
Derived derived;
derived.func();
}
/*The output will be:
I am base class
I am derived class
*/