【发布时间】:2011-05-26 18:29:54
【问题描述】:
我有一个函数用于在设置到缓冲区时强制类型匹配:
void SetUInt8(size_checker<uint8_t> val)
{
// make some static checks
}
通常,它是这样调用的:
// compile error, since you might mean to call the SetUInt() function
int myvar = 10;
SetUInt8(myvar);
// works fine
int8_t myvar = 1;
SetUInt8(myvar);
此调用会导致警告,因为 30 被解释为 int:
SetUInt8(30);
但我真的希望这一切正常,因为 30
template<size_t T>
void SetUInt8()
{
ASSERT(T < 256);
// do other stuff
}
当然会像这样使用:
SetUInt8<30>();
或者,我可以在调用函数时进行强制转换:
SetUInt8(uint8_t(30U));
是否有其他方法可以解决将 30 转换为 int 或检测其实际值(如果它是编译时间常数)的问题?
【问题讨论】:
-
@ildjarn:范围检查非类型模板参数;这当然是不同的(而且更难)。
-
@MSalter :我不明白为什么不能为文字提供重载(这是导致警告的原因),它会进行范围检查,然后将其实际工作委托给现有的重载。 ..
-
@ildjarn:C++ 没有文字重载。
-
@MSalters :我的意思是
SetUInt8<30>();与SetUInt8(30);(抱歉,我认为这很明显)。