模板类结构与元函数

发布时间:2024年01月20日

请看下面元函数_if:

template <bool B, typename L, typename R>
struct _if
{
?? ?typedef R type;
};

template <typename L, typename R>
struct _if<true, L, R>
{?
?? ?typedef L type;
};

?

执行以下代码(1):

#include<iostream>

/// <summary>
/// _if结构
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
/// <typeparam name="B"></typeparam>
template <bool B, typename L, typename R>
struct _if
{
	typedef R type;

	_if()
	{
		std::cout << "结构1" << "\n";
	}
};

 

void main()
{
	//std::string var1 = "text"
	_if<true, int, std::string>::type var1 = "text";

	_if<true, int, std::string> a1;

}

输出:

现在上面代码中再加一个_if结构2

/// <summary>
/// _if结构2
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
template <typename L, typename R>
struct _if<true, L, R>
{
?? ?typedef L type;
};

/// <summary>
/// _if结构
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
/// <typeparam name="B"></typeparam>
template <bool B, typename L, typename R>
struct _if
{
	typedef R type;

	_if()
	{
		std::cout << "结构1" << "\n";
	}
};

/// <summary>
/// i_if结构2
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
template <typename L, typename R>
struct _if<true, L, R>
{
	typedef L type;
};




void main()
{
	//std::string var1 = "text"
	_if<true, int, std::string>::type var1 = "text";

	_if<true, int, std::string> a1;

}

执行结果:

为什么编译不过,因为现在用的是结构:

也就是说:_if<true, int, std::string>::type var1 => int (返回整型),修改代码:

#include<iostream>

/// <summary>
/// _if结构
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
/// <typeparam name="B"></typeparam>
template <bool B, typename L, typename R>
struct _if
{
	typedef R type;

	_if()
	{
		std::cout << "结构1" << "\n";
	}
};

/// <summary>
/// i_if结构2
/// </summary>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
template <typename L, typename R>
struct _if<true, L, R>
{
	typedef L type;
	_if()
	{
		std::cout << "结构2" << "\n";
	}
};




void main()
{ 
	_if<true, int, std::string>::type var1 = 5;
	_if<false, int, std::string>::type var2 = "text";

	_if<true, int, std::string> a1;
	_if<false, int, std::string> a2;
}

输出:

这就是元函数_if原理:

?_if 原函数:

template <bool B, typename L, typename R>
struct _if{	typedef R type;};

template <typename L, typename R>
struct _if<true, L, R>{ 	typedef L type;};

文章来源:https://blog.csdn.net/weixin_42944928/article/details/135720955
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。