Function and class templates

Status
Not open for further replies.

Projectitis

Well-known member
Hi all,

I have a class MyClass with templated property x.
I want to use the class with float properties until the end, when I want to get a copy of it with uint16_t properties.
How can I achieve this using the power of templates? I feel like I'm 99% there. The compiler doesn't like the nested template (or doesn't like applying it to method only).

Here is what I want to do:
Code:
// Create with floats
MyClass<float>* f = new MyClass<float>( 128.0 );

// Do stuff
// ...

// Now convert to int16_t
MyClass<int16_t>* s = f->cloneAs<int16_t>();

Here's the example class. This is very simplified. My actual class has many properties and methods.
Code:
template <class T>
class MyClass {
	
	public:
		MyClass( T x ) {
			this->x = x;
		}

		T x;

		template <Class U> // <<< I can't put this here. Compiler complains
		MyClass<U>* MyClass::cloneAs() {
			return new MyClass<U>( (U)this->x );
		}

}

p.s. I do not want to do this (i.e. I do not want to have to know the type to clone to ahead of time):
Code:
template <class T, class U>
class MyClass {
	
	public:
		MyClass( T x ) {
			this->x = x;
		}

		T x;

		MyClass<U>* MyClass::cloneAs() {
			return new MyClass<U>( (U)this->x );
		}

}

// I do not know the type to clone to ahead of time
MyClass<float, int16_t>* f = new MyClass<float, int16_t>( 128.0 );
 
Last edited:
False alarm. This actually works. The error was me spelling class with a capital C in one place:
Code:
template <Class U> // Wrong
template <class U> // Correct
 
Status
Not open for further replies.
Back
Top