检查是否存在嵌套类型的别名并有条件设置类型别名
我不知道如何根据这样的输入参数中的类型别名有条件地设置类型的别名。
struct a { using type = int; }
template <typename T> struct wrapper {
using inner_t = ???how???; // if T::type exists, use T::type, else T
};
static_assert(std::is_same<wrapper<int>::inner_t, int>, "expected int");
static_assert(std::is_same<wrapper<a>::inner_t, int>, "expected inner type: int");
一个天真的尝试就像std ::条件&lt; std :: is_class&lt; t&gt; t :: type,type,t&gt;
如果存在type> type
type type 别名是先决条件,但远非安全,还没有检查is_alias_present&lt; t,type&gt;
之类的检查。除此之外,t :: Type
可能并不存在导致编译器错误的所有类型。
Apearthy std :: fastiment :: superiment :: is_detected 不幸的是,但不幸的是,不幸的是目前。
不确定是否像boost :: mp11
或boost :: hana
这样的好方法是完成此操作的好方法。
I wonder how to conditionally set a type alias, based on the existance of a type alias in input argument like this.
struct a { using type = int; }
template <typename T> struct wrapper {
using inner_t = ???how???; // if T::type exists, use T::type, else T
};
static_assert(std::is_same<wrapper<int>::inner_t, int>, "expected int");
static_assert(std::is_same<wrapper<a>::inner_t, int>, "expected inner type: int");
One naive attempt is like std::conditional<std::is_class<T>, T::type, T>
if the existence of a type
alias is a prerequisite, but is far from being safe, lacking a check for something like is_alias_present<T, type>
. Besides that T::type
is potentially not existing for all types resulting in a compiler error.
Apearently std::experimental::is_detected looks promising, but unfortunately not an option for now.
Not sure if metaprogramming libraries like boost::mp11
or boost::hana
are a good approach to get that done.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
借助
C ++ 17中的C ++ 20概念,您可以使用
void_t
来检测t :: Type
demo
With the help of C++20 concepts
In C++17, you can use
void_t
to detect the validity ofT::type
Demo
一种选择是像这样的作品中编写类型特征
,然后在包装器中使用它来使用
Sfinae,而如果
typename t :: Type
在std :: void_t&lt; typeName t :: type&gt;
然后丢弃了type_member
的专业化,我们回到了非类型成员专业化。One option is to write a type trait like
and then you would use it in wrapper like
This works by leveraging SFINAE and if
typename T::type
is ill-formed instd::void_t<typename T::type>
then that specialization oftype_member
is discarded and we fall back to the non-type member specialization.有两件事,要检测存在的特征和懒惰的评估。
在C ++ 20中,可以使用
需要轻松完成这些特征
然后懒惰评估:
There are 2 things, the traits to detect presence, and the lazy evaluation.
In C++20, the traits can be done easily with
requires
Then the lazy evaluation: