常用的萃取总结

元素类型Trait
• 返回值类型Trait
• 类型标签分发(Tag Dispatch)
• 判断式(Predicate Trait )
• 类型转换函数Trait

//1.类型萃取,值萃取

template<typename T>
struct SumT
{
	using SumType = T;
};


template<>
struct SumT<char>
{
	using SumType = int;
	constexpr static int initvalue = 0;
};

template<>
struct SumT<int>
{
	using SumType = long;
	constexpr static long initvalue = 10;
};

template<>
struct SumT<long>
{
	using SumType = long long;
	constexpr static SumType initvalue = 0;
};

template<typename T>
auto GetSum(const T* begin, const T* end)
{
	using mytype = typename SumT<T>::SumType;
	mytype total = SumT<T>::initvalue;
	while (begin != end)
	{
		total += *begin;
		begin++;
	}

	return total;
}

int main1()
{
	//类型萃取,值萃取
	int a[5] = {1,2,3,4,5};
	printf("%p %p %p\n",&a[0],&a[1],&a[2]);
	printf("%p %p %p\n", a, a+1, a+2);
	printf("%p %p %p\n", &a, &a + 1, &a + 2);

	auto x = GetSum(a,a+5);
	cout << x << endl;
	system("pause");
	return 0;
}

//2.类型标签分发

template<typename Iter>
using Iter_Category = typename iterator_traits<Iter>::iterator_category;

template<typename Iter>
void process_tag(Iter start, Iter end, forward_iterator_tag)
{
	cout << "处理 forward_iterator" << endl;
}

template<typename Iter>
void process_tag(Iter start, Iter end, random_access_iterator_tag)
{
	cout << "处理 random_access_iterator" << endl;
}


template<typename Iter>
void process(Iter start, Iter end)
{

	process_tag(start, end, Iter_Category<Iter>{});

}

int main3()
{

	vector<int> v{ 1,2,3,4,5 };
	process(v.begin(), v.end());

	forward_list<int> l = { 7, 5, 16, 8 };
	process(l.begin(), l.end());

	system("pause");
	return 0;
}


//3.判断式

template<bool val>
struct BoolConst
{
	constexpr static bool value = val;
};

using TrueType = BoolConst<true>;
using FalseType = BoolConst<false>;

template<typename T1,typename T2>
struct IsSameT:FalseType
{

};

template<typename T>
struct IsSameT<T,T> :TrueType
{

};


template<typename T>
void processImpl(T t,TrueType)
{
	cout << "(t,ture)\n";
}


template<typename T>
void processImpl(T t, FalseType)
{
	cout << "(t,false)\n";
}

template<typename T>
void process(T t)
{
	processImpl(t, IsSameT<T, int>{});
}

int main()
{

	process(1.2);
	process(10);

	system("pause");
	return 0;
}

更多模板相关技术可看:《模板与泛型编程》

你可能感兴趣的:(C/C++基础,c++)