【发布时间】:2017-03-05 21:36:11
【问题描述】:
是否可以根据模板参数的值有条件地在函数中编译语句?例如:
template<typename T, bool chk>
class subject
{
public:
// the ideal case
void doSomething(T new_val)
{
if(chk)
{
if(new_val != val)
//do_something only if new_val is different from val
}
else
{
//do_something even if new_val and val are equal
}
}
//or if that's not possible, if chk = 0 use this method
void doSomething(T new_val)
{
//do_something even if new_val and val are equal
}
// and if chk = 1 use this method
void doSomething(T new_val)
{
if(new_val != val)
//do_something only if new_val is different from val
}
T val;
};
catch 是基于 chk 的值,我什至不希望将语句 if(new_val!=val) 编译到函数中(因为这样使用的每个类型 T 都必须定义一个 != 运算符)。
我想这种方法的一个缺点是 foo<int,0> 和 foo<int,1> 是不同的类,因此不可能定义一个不关心 chk 是 0 还是 1 的函数(比如 watch(foo<int>)) .
我正在查看的应用程序是观察者,对于某些类型,我只希望在值实际更改时通知观察者,而对于其他类型,我希望始终通知观察者(对于那些我不'不想定义一个 != 运算符)。
如果没有两个单独的类,这可能吗?
【问题讨论】: