【发布时间】:2017-04-19 10:12:49
【问题描述】:
在编写自定义类型特征时,我经常从标准库类型特征中派生出它们,如下所示:
template<typename T>
struct some_type_trait:
std::is_arithmetic<T>
{};
但是,我有时想知道从标准库类型特征的type 成员类型继承是否更干净:
template<typename T>
struct some_type_trait:
std::is_arithmetic<T>::type
{};
总体思路是最终只有从std::bool_constant 的继承很重要,但事实上我们在第一个示例中继承自std::is_arithmetic 而不是直接从std::bool_constant 继承(如在第二个示例中)可通过多态性或 std::is_base_of 等实用程序观察到。
要点是通过type 成员类型直接从bool_constant 继承感觉更简洁,因为它正是我们想要的。但是,从std::is_arithmetic 继承会稍微短一些,并且提供基本相同的行为。那么......在选择一个或另一个(正确性,编译时间......)时我可能会错过任何微妙的优势吗?与直接从底层 bool_constant 继承相比,是否存在从 std::is_arithmetic 继承可能会改变应用程序行为的微妙场景?
【问题讨论】:
-
那是一些高质量的自行车:D
-
FWIW,en.cppreference.com 上的“可能实现”直接继承
std::integral_constant<bool, some_check>。遵循这种“风格”,您的示例将继承自std::integral_constant<bool, std::is_arithmetic<T>::value>。 -
@DanielJour 如果我没记错的话,从
std::integral_constant继承对于类型特征是强制性的。问题是通过::type直接从std::integral_constant派生还是通过类型特征本身间接派生更好。也许我不明白你的评论:/ -
虽然我对直接从类型特征继承与使用
type成员类型相比是否存在不利/可能的陷阱非常感兴趣。 -
我认为您需要从
std::is_arithmetic<T>继承才能选择对特征进行惰性评估。拥有它很有用。如果你想要一个“干净”的界面,你也可以使用template<class T> using some_type_trait_t = some_type_trait<T>::type。
标签: c++ c++11 typetraits