Marcin K.
Marcin K.

Reputation: 843

How to implement decltype functionality - pre c++11, compile time

I have a question if there is a way to implement decltype keyword functionality pre c++11.

I have a simplified class of vector

template <class T>
struct MyVector {

    typedef T ElementType;

    T* arrayPtr;
    uint64_t numberOfElements;
};

I want to be able to get the type T in a universal MACRO that will be usable with this MyVector

#define ALLOCATE_SPACE(VectorRef, numberOfItems) \
{ \
    arrayPtr = new decltype(VectorRef)::ElementType[numberOfItems]; \ \
} \

The problem is I can't use c++11 stuff. The perfect solution would be to make it 100% compile time type deduction.

Can anyone help me with this issue?

Best Regards

Upvotes: 1

Views: 794

Answers (1)

Andr&#233; Bergner
Andr&#233; Bergner

Reputation: 1439

This is possible. There is a boost macro accomplishing this magic:

#include <boost/typeof/typeof.hpp>
#include <iostream>
#include <typeinfo>

int main() {
    int a; float b;
    BOOST_TYPEOF(a+b) c = a+b;
    std::cout << typeid(c).name() << std::endl;
}

prints f (float). Live Demo

Though, as already pointed out in the comments, you don't need this for your problem. A simple template function would do the job.

Upvotes: 1

Related Questions