编译器没有警告精度损失?

nij*_*sen 6 c++ g++ compiler-warnings c++11

我最近一直在玩C++ 11,并提出了以下sum函数:

template <typename T>
inline T sum(const std::function<T (int)> &f, int initial, int end)
{
    T retval = 0;
    for(int k = initial; k <= end; k++) {
        retval += f(k);
    }
    return retval;
}
Run Code Online (Sandbox Code Playgroud)

我的想法是,我可以传递一个lambda函数,因此对数学和有一个整洁可读的函数.然后我尝试了以下内容:

int main()
{
    std::array<double, 2> arr1 = {{ 0.5, 1.5 }},
                          arr2 = {{ 1.5, -0.5 }};
    auto n = sum<int>([&](int k) { return arr1[k]*arr2[k]; }, // Precision loss!
                      0, 1);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我使用g ++ 4.6.3编译了这个:g++ -Wall -pedantic -std=c++0x -o test main.cpp并没有给出我在源代码注释中注释的精度损失的任何警告.

这里几乎给出了sum<int>一个不好的事情,但在更复杂的环境中可能并不那么明显.编译器是否应该注意到我的lambda函数的返回值double并且警告我在投射到时会丢失精度int?有没有具体的原因呢?

MSa*_*ers 5

似乎完全合理.你告诉编译器不要打扰模板参数扣除(即使用sum<double>),而是明确告诉它使用sum<int>.这和显性演员一样好.

[编辑]怎么样

template <typename F>
auto sum(F const& f, int initial, int end) -> decltype(f(initial))
{
    auto retval = f(initial++);
    while(initial <= end) {
        retval += f(initial++);
    }
    return retval;
}
Run Code Online (Sandbox Code Playgroud)