模板类结构与元函数

本文详细介绍了C++中的元函数_if结构,展示了如何使用模板和类型别名进行条件编译,并演示了在不同条件下的执行结果。编译问题在于对不同类型返回值的错误处理。
摘要由CSDN通过智能技术生成

请看下面元函数_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;};

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值