Re: How to get rid of the new-initializer in a new-expression
Matthias Hofmann wrote:
Hello everyone!
I have written a memory tracker using macros, and everything works fine
unless the new-expression contains a new-initializer. Please take a look at
the following example:
template <class T> T* TrackNew( T* ptr ) { return ptr; }
#define NEW( T ) TrackNew<T>( new T )
struct X
{
X() {}
X( int ) {}
};
int main()
{
// Works fine.
X* p1 = NEW( X );
// Fails to compile.
X* p2 = NEW( X( 2 ) );
return 0;
}
The second use of the NEW macro expands to:
X* p2 = TrackNew<X( 2 )>( new X( 2 ) );
Obviously, this should be:
X* p2 = TrackNew<X>( new X( 2 ) );
Can anyone please tell me a portable way of getting rid of the
new-initializer in the new-expression? Like in the following pseudo code:
#define NEW( T ) TrackNew<REMOVE_NEW_INITIALIZER( T )>( new T )
Would you consider something like this?
template<typename T>
T* New() { return new T; }
template<typename T, typename U>
T* New(U const& u) { return new T(u); }
template<typename T, typename U, typename V>
T* New(U const& u, V const& v) { return new T(u, v); }
// ... Up to some large number of arguments.
struct X {
X() { }
X(int) { }
X(int, double) { }
};
int main() {
X* p1 = New<X>();
X* p2 = New<X>(2);
X* p3 = New<X>(2, 3.0);
// ...
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]