0
0

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 3 years have passed since last update.

C++11 で std::vector<T> な変数から型 T を取得する

Last updated at Posted at 2020-06-03

背景

std::vector ということがわかっている変数から, 型 T を抽出したい.

方法

std::vector<float> a;

using t = decltype(*a.begin());

static_assert(std::is_same<t, float>::value == true, "type must be float");

*a.data() でもいいかもしれません.

a[0] でも OK でした.

配列のインデックスを取るのは, カラの配列時 seg fault しそうでちょっと抵抗がありますが, sizeof はコンパイル時の処理だからか, 実のところカラの配列に対して行っても実行時問題ありませんでした(asan でも問題なかった)

おまけ

std::vector<float *> など, ポインタの可能性のあるときからポインタ除去した型がほしい.

std::remove_pointer を使います.

ポインタで無い場合はなにもしないので汎用に使えます.

ただ, この場合 std::decay と組み合わせないとうまくいかないです.

decayメタ関数
https://faithandbrave.hateblo.jp/entry/20120416/1334563367

C++ Get Vector type
https://stackoverflow.com/questions/12490508/c-get-vector-type/53259979#53259979

こんな感じになります.

std::vector<float *> b;
using t = std::remove_pointer<std::decay<decltype(*b.begin())>::type>::type;
// => t = `float`

この場合, std::vector<float[2]> b なケースでも float が型として取得できます!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?