如题。不过不能给它obj-c用template。
objeTest.h
#import <Foundation/Foundation.h>
template<class T>
class Base
{
public:
T data;
public:
Base(T val=T())
{
data =val;
}
~Base(){}
void SetValue( T val)
{
data =val;
}
const T GetValue()const
{
return data;
}
};
//the template function determine whether the two object are equal.
template<class T>
bool IsCompare(const T *rval, const T *lval)
{
return [rval isC: lval];
}
@interface ObjTest : NSObject {
Base<int> * basedata;
}
- (id)initWithValue:(int) val;
- (void)delloc;
-(void)data:(int)val;
-(int)getdata;
-(NSString*)description;
//for the future,the template invoke it.
-(BOOL) isC:(ObjTest*)lval;
@end
objTest.mm(note this post file name)
#import "ObjTest.h"
#import "Engine.h"
@implementation ObjTest
- (id)initWithValue:(int) val
{
self = [super init];
if (self)
{
basedata = new Base<int>(val);
}
return self;
}
- (void)delloc
{
delete basedata;
//[super delloc];
}
-(void)data:(int)val
{
basedata->SetValue(val);
}
-(int)getdata
{
return basedata->GetValue();
}
-(NSString*)description
{
// NSString *formatstr = [[NSString alloc] initWithFormat:@"value is now:%i",(basedata->GetValue()) ];
// return [formatstr autorelease];
return [NSString stringWithFormat:@"value is now:%i",(basedata->GetValue()) ];
}
- (BOOL) isC:(ObjTest*) lval
{
BOOL breturn = NO;
if ([self getdata] == [lval getdata]) {
breturn =YES;
}
return breturn;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
// NSMutableArray *array =
//
// [NSMutableArray arrayWithObjects:@"Miguel", @"Ben", @"Adam", @"Melissa", nil];
//
//
//
// NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'a'"];
//
// NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];
//
//compare the objects using the template function.
id obj = [[ObjTest alloc] initWithValue:101 ];
NSLog(@"value is %@",obj);
id obj2 = [[ObjTest alloc] initWithValue:101 ];
NSLog(@"value is %@",obj2);
bool bresult = IsCompare<ObjTest>(obj,obj2);
[obj release];
[obj2 release];
[pool drain];
return 0;
}