C++:auto和decltype返回类型后置

/ C++ / 没有评论 / 436浏览

为什么要有后置类型? 是为了解决函数返回值类型依赖于参数而导致难以确定返回值类型的问题。

#include<iostream>

using namespace std;
 
template <typename T, typename U>
auto add(T t,U u) -> decltype(t+u)
{
	return t+u;
}

int main()
{
	int a=1;
	float b=2.0;

	auto c = add<decltype(a+b)>(a,b);

	cout << c << endl;
	return 0;
}
#include <iostream>

//C++11
//template <typename T>
//auto Cam(T&& param)->decltype(std::forward<T>(param))
//{
//	param = 100;
//	return std::forward<T>(param);
//}

// C++14
template <typename T>
decltype(auto) Cam(T&& param)
{
	param = 100;
	return std::forward<T>(param);
}


int main()
{
	std::cout << Cam(100) << std::endl;
	return 0;
}
#include<utility>
#include<iostream>

int test(int a, int b) {
	int c = a + b;
	std::cout << "Run Test" << c << std::endl;
	return c;
}

/* 无法通过编译
template<typename Fn, typename... Args>
decltype(Fn(Args...)) test_decltype3(Fn f, Args... args) {
	std::cout<<"Run Test_Decltype3"<<std::endl;
	auto res = f(args...);
	return res;
}
*/

template<typename Fn, typename... Args>
auto test_decltype2(Fn f, Args... args) -> decltype(f(args...)) {
	std::cout << "Run Test_Decltype2" << std::endl;
	auto res = f(args...);
	return res;
}

template<typename Fn, typename... Args>
decltype(std::declval<Fn>()(std::declval<Args>()...)) test_decltype1(Fn f, Args... args) {
	std::cout << "Run Test_Decltype1" << std::endl;
	auto res = f(args...);
	return res;
}

int main(int agrc, char *argv[]) {

	auto res0 = test_decltype1(test, 1, 2);
	auto res1 = test_decltype2(test, 1, 3);
	std::cout << "Main Res0: " << res0 << std::endl;
	std::cout << "Main Res1: " << res1 << std::endl;
	return 0;

}