模板类型推导
Template type deduction
我在模板参数列表中遇到过几次 class = std::enbale_if<condition, type>::type
,我知道 std::enable_if<B,T>::type
的作用但不确定 class =
的作用?我的意思是我知道 class type_name = type
但为什么 class =
中没有类型名称?我什么时候使用它?
编辑:此示例来自 here
template <class T, class U, class = typename enable_if
<is_lvalue_reference<T>::value ? is_lvalue_reference<U>::value : true>::type>
inline T&& forward(U&& u)
{
return static_cast<T&&>(u);
}
这是一个未命名的模板类型参数。就像你可以在未使用的函数参数中省略变量名一样,你可以在未引用的模板参数中省略参数名。
在 std::enable_if<...>::type
的特定情况下,这仅用于 SFINAE 目的。具体来说,如果enable_if
中的boolean为false,模板参数推导就会失败。
这是SFINAE(替换失败不是错误)。下面是两个示例,其中对 struct 和 class 施加了约束,以禁止使用不正确的类型进行实例化。
but not sure what class = does ? I mean I know class type_name = type but why there is no type name in class = ? when would I use it ?
这是一个未命名的模板参数类型,您可以给它起一个名字,但不需要它,因为该参数仅在重载结果期间使用(以删除无效候选者)。实际给它命名可能会显示警告。
http://coliru.stacked-crooked.com/a/25162a3eb107943f
// Allow only T to be floating type (!! actually static_assert would be preferred here)
template<class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
struct foo {
};
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even(T i) {return !bool(i%2);}
int main()
{
// foo<int> f; //error
foo<float> f; //ok
//is_even(1.1); //error
is_even(1); //ok
return 0;
}
[编辑]
我必须说上面的示例不是最好的,建议使用 static_assert,因为它可以生成信息性错误消息。 SFINAE 不应用于参数验证,而是用于根据提供的类型选择另一个实现。
我在模板参数列表中遇到过几次 class = std::enbale_if<condition, type>::type
,我知道 std::enable_if<B,T>::type
的作用但不确定 class =
的作用?我的意思是我知道 class type_name = type
但为什么 class =
中没有类型名称?我什么时候使用它?
编辑:此示例来自 here
template <class T, class U, class = typename enable_if
<is_lvalue_reference<T>::value ? is_lvalue_reference<U>::value : true>::type>
inline T&& forward(U&& u)
{
return static_cast<T&&>(u);
}
这是一个未命名的模板类型参数。就像你可以在未使用的函数参数中省略变量名一样,你可以在未引用的模板参数中省略参数名。
在 std::enable_if<...>::type
的特定情况下,这仅用于 SFINAE 目的。具体来说,如果enable_if
中的boolean为false,模板参数推导就会失败。
这是SFINAE(替换失败不是错误)。下面是两个示例,其中对 struct 和 class 施加了约束,以禁止使用不正确的类型进行实例化。
but not sure what class = does ? I mean I know class type_name = type but why there is no type name in class = ? when would I use it ?
这是一个未命名的模板参数类型,您可以给它起一个名字,但不需要它,因为该参数仅在重载结果期间使用(以删除无效候选者)。实际给它命名可能会显示警告。
http://coliru.stacked-crooked.com/a/25162a3eb107943f
// Allow only T to be floating type (!! actually static_assert would be preferred here)
template<class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
struct foo {
};
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even(T i) {return !bool(i%2);}
int main()
{
// foo<int> f; //error
foo<float> f; //ok
//is_even(1.1); //error
is_even(1); //ok
return 0;
}
[编辑]
我必须说上面的示例不是最好的,建议使用 static_assert,因为它可以生成信息性错误消息。 SFINAE 不应用于参数验证,而是用于根据提供的类型选择另一个实现。