Help us understand the problem. What is going on with this article?

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

背景

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 でした.

https://stackoverflow.com/questions/1665018/memset-on-vector-c

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

おまけ

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

std::remove_pointer を使います.

https://en.cppreference.com/w/cpp/types/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 が型として取得できます!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした