Define an object from a template type

Is there a way to define the object in a way like the line below <

template<typename T>
struct A {
    T *data;
    //...   
    typedef T data_type;
};

int main() {
    A<int>::data_type a;    // ok

    A<int> obj;
    obj.data_type b;        // <-- is it possible to do something like this??
}

      

Thank!

Massimo

+3


source to share


3 answers


Since C ++ 11, you can:

decltype(obj)

is evaluated at compile time and is a type obj

. It can be used whenever the type is used.



So you can write decltype(obj)::data_type b;

decltype

is a keyword and is especially useful in general programming.

+2


source


You can use decltype

in expressions
. Code for your case:



decltype(obj)::data_type b;

      

+4


source


This seems to work fine; use decltype () for C ++ 11; you can try typeof () pre C ++ 11 typeof () in gcc: https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

#include <iostream>
using namespace std;

template<typename T>
struct A {
  T *data;
  //...   
  typedef T data_type;
};

int main() {
  A<int>::data_type a;    // ok

  A<int> obj;
  decltype(obj)::data_type b;        // <-- is it possible to do something like this??
}

      

+1


source







All Articles