z****p 发帖数: 138 | 1 我在写一个generic 的函数比较两个class是否相等, 其中一个相等条件是这两个
class的ID 相同,可不可以在template里要求传入的类型必须有ID这个member
variable呢?怎样才能做得到呢?
谢谢 |
c*******a 发帖数: 18 | 2 one way i can think is let every class inheredited from
a base class with id variable in it, and in your function
you use base class to do comparison
【在 z****p 的大作中提到】 : 我在写一个generic 的函数比较两个class是否相等, 其中一个相等条件是这两个 : class的ID 相同,可不可以在template里要求传入的类型必须有ID这个member : variable呢?怎样才能做得到呢? : 谢谢
|
z****p 发帖数: 138 | 3 Yes, this is one solution. However, the project is close to the end. The
design change is impractical at this stage.
Thanks.
【在 c*******a 的大作中提到】 : one way i can think is let every class inheredited from : a base class with id variable in it, and in your function : you use base class to do comparison
|
c*****t 发帖数: 1879 | 4 It is a template... You just assume the functions / data members exist.
It is the responsibility of the classes this template uses to have
the functions / data member.
【在 z****p 的大作中提到】 : 我在写一个generic 的函数比较两个class是否相等, 其中一个相等条件是这两个 : class的ID 相同,可不可以在template里要求传入的类型必须有ID这个member : variable呢?怎样才能做得到呢? : 谢谢
|
z***e 发帖数: 14 | 5 1. You can dynamic-cast the in object to target types. If it fails, do
nothing. Otherwise, get the id from the casted type.
2. If there is no target type known-in-advance, for example you don't want
to list all possible target types or it is created by third party, you can
use template constrain in definition. Some thing like this:
bool Comparer (T t1, T t2) where T : IIDBase
{
return t1.Equals(t2);
}
IIDBase is the interface:
Interface IIDBase
{
int GetID();
}
Then derive a
【在 z****p 的大作中提到】 : 我在写一个generic 的函数比较两个class是否相等, 其中一个相等条件是这两个 : class的ID 相同,可不可以在template里要求传入的类型必须有ID这个member : variable呢?怎样才能做得到呢? : 谢谢
|
z****p 发帖数: 138 | 6 Thanks, your second solution is exactly what I am looking for. I remember
somewhere I saw this kind of specification, but forget it.
【在 z***e 的大作中提到】 : 1. You can dynamic-cast the in object to target types. If it fails, do : nothing. Otherwise, get the id from the casted type. : 2. If there is no target type known-in-advance, for example you don't want : to list all possible target types or it is created by third party, you can : use template constrain in definition. Some thing like this: : bool Comparer (T t1, T t2) where T : IIDBase : { : return t1.Equals(t2); : } : IIDBase is the interface:
|
t****t 发帖数: 6806 | 7 what about just use
std::tr1::is_same::value
【在 z****p 的大作中提到】 : 我在写一个generic 的函数比较两个class是否相等, 其中一个相等条件是这两个 : class的ID 相同,可不可以在template里要求传入的类型必须有ID这个member : variable呢?怎样才能做得到呢? : 谢谢
|