【问题标题】:C++ detecting const int passed into functionC ++检测传递给函数的const int
【发布时间】: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&lt;30&gt;();SetUInt8(30);(抱歉,我认为这很明显)。

标签: c++ templates casting


【解决方案1】:

我最好的想法是一个模板,静态断言函数,static_casts 为您服务:

template<size_t size>
void SetUInt8()
{
    BOOST_STATIC_ASSERT(size < 256);
    SetUInt8(static_cast<uint8_t>(size));
}

像你一样调用它:SetUInt8&lt;50&gt;();

因为它应该总是被内联,所以没有性能开销,它会进行编译时范围检查。如果编译器足够聪明,不会在值明显适合较小类型的范围时发出警告,那就更好了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多