请看下面元函数_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;
}
执行结果:
为什么编译不过,因为现在用的是结构:
文章来源:https://www.toymoban.com/news/detail-809442.html
也就是说:_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原理:
文章来源地址https://www.toymoban.com/news/detail-809442.html
_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;};
到了这里,关于模板类结构与元函数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!