Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type trait through a variable of the type

Tags:

c++

I'd like to test a property of the type of a variable. I do can it, but the code is too verbose.

Consider an example, in which I define a variable of the same type as the type of a value in a container:

#include <vector>

int main() {
  std::vector<int> v, &rv=v;

  // ‘rv’ is not a class, namespace, or enumeration
  //rv::value_type i1;

  // Ok
  decltype(v)::value_type i2;

  // decltype evaluates to ‘std::vector<int>&’, which is not a class or enumeration type
  //decltype(rv)::value_type i3;

  // Ok
  std::remove_reference<decltype(rv)>::type::value_type i4;
}

I can live with decltype, but adding std::remove_reference is too much. Are there any nice way to shorten the code, without defining auxiliary templates?

like image 753
olpa Avatar asked Sep 11 '25 13:09

olpa


1 Answers

You can shorten that with one of

std::decay_t<decltype(rv)>::value_type i4 = 42;

or

std::decay_t<decltype(*std::begin(rv))> i4 = 42;
like image 143
Jarod42 Avatar answered Sep 13 '25 02:09

Jarod42