C+ 17替代C+ 20;关键词
C ++ 20引入了许多改进,例如需要
,概念
s,约束,模块
等等 - 您在C ++中真正错过的功能17 。
如何在C ++ 17中实现具有条件构造函数的方案,这看起来像以下C ++ 20示例(使用需要
)?
template <typename T> concept has_type = requires { typename T::type; };
template <typename T>
class someClass {
public:
using data_t = typename std::conditional_t<has_type<T>, T, std::type_identity<T> >::type;
constexpr someClass(T const& _a, T const& _b) requires std::is_arithmetic_v<T> : a{_a}, b{_b} {}
constexpr someClass(data_t const& _a, data_t const& _b,) requires has_type<T> : a{_a}, b{_b} {}
private:
const data_t a, b;
};
必须在t
的情况下使用一个构造函数(int
,float
,double
,。 ..)。 另一个构造函数需要捕获t
是具有嵌套type
别名的类/结构的情况(例如代码>)。
C++20 introduced many improvements like requires
, concept
s, constraints, modules
and much more - functionality you really miss in C++17.
How can a scenario having conditional constructors be implemented in C++17, that could look like the following C++20 example (using requires
)?
template <typename T> concept has_type = requires { typename T::type; };
template <typename T>
class someClass {
public:
using data_t = typename std::conditional_t<has_type<T>, T, std::type_identity<T> >::type;
constexpr someClass(T const& _a, T const& _b) requires std::is_arithmetic_v<T> : a{_a}, b{_b} {}
constexpr someClass(data_t const& _a, data_t const& _b,) requires has_type<T> : a{_a}, b{_b} {}
private:
const data_t a, b;
};
One constructor has to be used in case of T
is an arithmetic type (int
, float
, double
, ...).
Another constructor needs to catch the case of T
being a class/struct having a nested type
alias (e.g. struct x { using type=float; };
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 sfinae
//godbolt.org/z/gyejharsa“ rel =“ nofollow noreferrer”> demo
Using SFINAE
Demo