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