Effective Modern C++:decltyle,use {}

decltype用法:

In C++11, perhaps the primary use for decltypeis declaring function templates where the function’s return typedepends on its parameter types.

decltype 用于获得某个未知变量的类型,在什么情况下我们不知道变量的类型呢? 当然是使用template或auto的时候:

template<typename T>
void funcValue(T param)
{
	auto subParam = param;
	decltype(auto) subSubParam = subParam;
}

大括号用法

初始化使用大括号(统一初始化符号):

std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5 

初始化类成员函数直接用大括号:

class Widget {

private:
int x{ 0 }; // fine, x's default value is 0
int y = 0; // also fine
int z(0); // error!
}; 

总之,以前使用()和=的地方,统统用大括号代替,肯定没错

但是,大括号不允许隐式类型转换:

double x, y, z;
int sum1{ x + y + z }; // error! sum of doubles may  not be expressible as int

此外,当我们使用 std::initializer_list 初始化一个类时,必须使用大括号:

class Widget
{
public:
	Widget(std::initializer_list<int> il)
	{
		int i = 0;
		for (auto itre = il.begin(); itre != il.end(); itre++,i++)
			m_l[i] = *itre;
	}
private:
	int m_l[256];
};

Widget w4{ 1,2,3,4 };

并且使用这种初始化方法不支持隐式类型转换

Wangxin -->

Wangxin

I am algorithm engineer focused in computer vision, I know it will be more elegant to shut up and show my code, but I simply can't stop myself learning and explaining new things ...