C++ boost::hana标记实现
我想知道当C++ boost::hana标记实现,c++,boost,c++14,partial-specialization,C++,Boost,C++14,Partial Specialization,我想知道当boost::hana::when案例没有案例库时,when专业化是如何工作的 boost::hana::tag\u的实现: template<bool condition> struct when; // forward declaration only template<typename T, typename = void> struct tag_of; template<typename T, typename> struct
boost::hana::when
案例没有案例库时,when
专业化是如何工作的
boost::hana::tag\u的实现:
template<bool condition>
struct when; // forward declaration only
template<typename T, typename = void>
struct tag_of;
template<typename T, typename>
struct tag_of : tag_of<T, when<true> >
{};
template<typename T, bool condition>
struct tag_of<T, when<condition> >
{
using type = T;
};
模板
结构时;//仅限远期申报
模板
结构标签;
模板
结构标记的:标记的
{};
模板
结构标签
{
使用类型=T;
};
以及一个测试示例:
struct my_tag {};
struct my_tag2 {};
namespace boost {
namespace hana {
template<class T>
struct tag_of<T, when<std::is_same<T, int>{}()> >
{
using type = my_tag;
};
template<class T>
struct tag_of<T, when<std::is_same<T, unsigned>{}()> >
{
using type = my_tag2;
};
}
}
int main()
{
using type = boost::hana::tag_of<int>::type;
std::cout << std::is_same<type, my_tag>{} << std::endl;
}
struct my_tag{};
结构my_tag2{};
名称空间提升{
名称空间hana{
模板
结构标签
{
使用类型=我的标签;
};
模板
结构标签
{
使用类型=my_tag2;
};
}
}
int main()
{
使用type=boost::hana::tag_of::type;
标准::cout
我想知道为什么std::is_same{}()
(或者与::value
相同)是比std::is_same{}()
更专业化的部分专门化,以及为什么如果两种情况的条件都为false,那么当更专业化时,
它不是更专业化。它们从来都不是可行的专业化。让我们看看当我们尝试实例化hana::tag_of
时会发生什么
填写默认模板参数。在本例中,第二个模板参数默认为void
,因此我们确实有hana::tag\u of
考虑哪些部分专门化是可行的。在这种情况下,没有一个是可行的-我们的类型(int
)不是引用或cv限定的,并且在
时它不是任何类型的。因为没有一个专门化是可行的,所以我们实例化主模板
的主标记u继承自的标记u。因此,现在我们需要实例化第二种类型,这意味着我们重新执行步骤2
现在,两种不同的专业化是可行的:
// from hana's core
template <typename T, bool condition>
struct tag_of<T, when<condition>>
// yours
template <typename T>
struct tag_of<T, when<std::is_same<T, int>{}()>>
这将在上面的第2步短路,跳过所有其他的实例化。它非常漂亮。谢谢。
template <>
struct tag_of<int, void> {
using type = my_tag;
};