代码之家  ›  专栏  ›  技术社区  ›  xmllmx

如果执行了分支,是否有一种有效的方法来断言constexpr?

  •  0
  • xmllmx  · 技术社区  · 1 年前
    int f(auto obj) {
        if constexpr (HasFastGetData<decltype(obj)>) {
            return obj.FastGetData();
        } else {
            return obj.GetData();
        }
    }
    
    int main() {
        B obj;
        f(obj);
        // How to verify obj.FastGetData(), rather than obj.GetData(), is executed?
    }
    

    以上面的代码为例:

    • 我有两节课 A & B .
    • A. 具有成员功能 int GetData() B 具有成员功能 int FastGetData() .
    • 这两个函数具有相同的对称性,但是 FastGetData GetData .
    • 我想要 f 以区分obj的类型以获得更好的性能。

    我只是想知道:

    有没有一种有效的方法来单元测试我的意图?

    2 回复  |  直到 1 年前
        1
  •  1
  •   user12002570    1 年前

    您可以添加 static_assert(HasFastGetData<B>) 在呼叫之后 f 或返回 std::pair 包含结果:

    方法1

    f(obj);
    //------------vvvvvvvvvvvvvvvvv--->condition of first branch goes here
    static_assert(HasFastGetData<B>); //this makes sure that the first branch if taken 
    
    

    方法2

    您也可以返回 std::对 (或具有合理命名成员的自定义结构)进行检查:

    std::pair<int,int> f(auto obj) {
        if constexpr (HasFastGetData<decltype(obj)>) {
            return {1, obj.FastGetData()};
        } else {
            return {0,obj.GetData()};
        }
    }
    int main() {
        B obj;
        std::pair<int, int> result = f(obj);
        if(result.first){} //first branch taken
        else{} 
        
    }
    
    
        2
  •  -2
  •   Nhat Nguyen    1 年前

    您可以使用GoogleTest,对函数FastGetData()断言EXPECT_CALL。