C++ 当<&燃气轮机;在boost中的特性。Hana有效吗?
我对C++ 当<&燃气轮机;在boost中的特性。Hana有效吗?,c++,c++14,boost-hana,C++,C++14,Boost Hana,我对std::enable_if有一些经验。IIRC,它是关于格式良好的表达式是否会导致true返回用户类型T(如果给定)或通过嵌套类型别名返回void template<bool,typename = void> struct enable_if; template<typename T> struct enable_if<true,T>{ using type = T; }; template <typename T, typename = v
std::enable_if
有一些经验。IIRC,它是关于格式良好的表达式是否会导致true
返回用户类型T(如果给定)或通过嵌套类型别名返回void
template<bool,typename = void>
struct enable_if;
template<typename T>
struct enable_if<true,T>{
using type = T;
};
template <typename T, typename = void>
struct base_template{
enum { value= false};
};
template <typename T>
struct base_template<T, typename enable_if<std::is_integral<T>::value>::type> {
enum { value= true};// something useful...
};
struct some{};
static_assert(base_template<some>::value,"F*"); //error: static assertion failed: F
static_assert(base_template<int>::value,"F*");
模板
结构启用_if;
模板
结构启用\u如果{
使用类型=T;
};
模板
结构基本模板{
枚举{value=false};
};
模板
结构基本模板{
枚举{value=true};//一些有用的东西。。。
};
构造一些{};
静态断言(基本模板::值,“F*”//错误:静态断言失败:F
静态断言(基本模板::值,“F*”;
但是在boost.Hana中,我看到了这个特性,它的实现是这样的
template <bool condition>
struct when;
template <typename T, typename = when<true>>
struct base_template{
enum { value= false};
};
template <typename T>
struct base_template<T, when<std::is_integral<T>::value>> {
enum { value= true};// something useful...
};
struct some{};
static_assert(base_template<int>::value,"F*");
static_assert(base_template<some>::value,"F*");<source>:28:15: error: static assertion failed: F*
模板
结构时;
模板
结构基本模板{
枚举{value=false};
};
模板
结构基本模板{
枚举{value=true};//一些有用的东西。。。
};
构造一些{};
静态断言(基本模板::值,“F*”;
静态断言(基本模板::值,“F*”);:28:15:错误:静态断言失败:F*
SFINAE在这里是如何工作的?虽然
std::is_integral::value
将导致false,但这并不意味着when
是格式错误的,应该将实例化分派到主类模板。我在这里遗漏了什么吗?这是相同的想法。如果或decltype
的使用方法基本相同,则可以使用enable\u。现在,您可能已经习惯于看到SFINAE的部分专业化,如下所示:
template<class T, class U = void>
struct Foo {};
template<class T>
struct Foo<T, decltype(T::bar())> {};
... Foo<X> ...
在这里,Foo
首先被编译器扩展为Foo
(因为您没有在“调用站点”提供U
,所以默认的U=when
被填充)。然后,编译器寻找类模板Foo
的最佳匹配专门化。如果when
实际上是when
,那么Foo[带T=X]
将是Foo
的完美匹配。否则,将使用通用的Foo[带T=X,U=when]
您可以用任意复杂的布尔表达式替换我的示例中的简单表达式T::baz
,只要它是constexpr可计算的。在最初的示例中,表达式是std::is_integral::value
我的2017年CppCon课程将介绍一些类似的示例。@ildjarn它们肯定不完全相同,因为enable\u if\u t
是一个类型别名,而是一个类模板,而与enable\u if\u t
不同,我也看不到在删除任何嵌套类型时。这是一个特殊的规则吗专门化的第二种类型是与默认参数匹配还是使用主模板?我知道发生了什么,但我不明白“为什么”。主要模板是“最不专业”的版本;部分专门化是“更专业化”。在所有其他条件相同的情况下,编译器将选择最专业化(最不通用)的版本,在这种情况下,这意味着选择部分专门化Foo[带T=X]
而不是不太专业化的Foo[带T=X,U=void]
。如果我们编写了一个完全专门化的模板结构Foo{}
,那么编译器就会选择Foo
,而不是不太专门化的Foo[使用T=X]
。这就是模板专门化工作的原因。
template<bool> struct when {};
template<class T, class U = when<true>>
struct Foo {};
template<class T>
struct Foo<T, when<T::baz>> {};
... Foo<X> ...