1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++のクラスでタグの存在を判定するメタ関数 (Lightweight Type Categorization Idiom)

Last updated at Posted at 2022-04-07

C++でクラスにタグのようなものを埋め込み,その存在の有無をコンパイル時に判定するためのメタ関数を実装したい.

#include <type_traits>

template<typename T, typename R=void>
struct enable_if_type {using type = R;};

template<typename T, typename R=void>
struct has_x_tag : std::false_type {};

template<typename T>
struct has_x_tag<T, typename enable_if_type<typename T::x_tag>::type> 
 : std::true_type {};

int main()
{
  struct A {};
  struct X {using x_tag = void;};

  static_assert(has_x_tag<A>::value, "");  // fail
  static_assert(has_x_tag<X>::value, "");  // pass
}

ポイントは2つ:

  1. タグは適当な型エイリアス using x_tag = void で定義
  2. 判定用メタ関数 has_x_tag<> は SFINAE で実装

このアイデアは Stack Overflow にて @JoelFalcou 氏が提案した "Lightweight Type Categorization Idiom" を拝借したものです:

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?