【问题标题】:coverage for enable_if template class functions in C++C++ 中 enable_if 模板类函数的覆盖率
【发布时间】:2020-12-24 10:19:06
【问题描述】:

我正在尝试为我的模板化数学课程生成准确的代码覆盖率。我默认使用here 中的技巧实例化模板类中的每个方法

template class Vector2D<float>;

这样覆盖率并不总是 100%,而是向我展示了从未调用过函数的地方。问题是,如果我更进一步并使用 type traits 为某些类型启用模板类的成员函数,那么这些的覆盖率又总是 100%。 gcov 和 llvm-cov 都表明没有生成这些函数。 我猜是因为这些函数在我的模板类中是它们自己的“模板”?

template<typename T>
class Vector2D {

...

template <class U = T>
typename std::enable_if<std::is_floating_point<U>::value, void>::type rotate(
T angle) {
    ...
    }
};

我如何(默认)实例化这些函数,以便覆盖率报告在它们从未被调用时以橙色/红色显示它们?

【问题讨论】:

  • 不确定但是...您是否尝试过将using 定义为using foo_type = decltype(std::declval&lt;Vector2D&lt;float&gt;&gt;().rotate(0.0f)) 或类似的东西?

标签: c++ templates code-coverage typetraits


【解决方案1】:

我最终显式实例化了模板成员函数(参见this post

template void Vector2D<float>::rotate<float>(float);

如果我确实没有在代码中显式调用它,那么覆盖率报告会将该函数显示为从未调用(橙色/红色)。

【讨论】:

    【解决方案2】:

    与类一样,函数/方法可以显式实例化:

    template
    typename std::enable_if<std::is_floating_point<F>::value, void>::type
    Vector2D<float>::rotate<float>(float);
    

    使用 C++20 requires,使用:

    template<typename T>
    class Vector2D {
    
    //...
    
        void rotate(T angle) requires(std::is_floating_point<T>::value) {
            //...
        }
    };
    

    我希望只需要显式的类实例化。

    【讨论】:

    • 不是 100% 我需要的,但你让我走上了正轨。谢谢!我将发布我对该问题的答案以供将来参考
    • 看来std::enable_if可以解决,所以你的答案和我的差不多。
    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 2012-01-22
    • 2014-08-16
    • 2014-03-08
    • 1970-01-01
    相关资源
    最近更新 更多