有没有有效的方法来断言 constexpr-if 分支已执行?

问题描述 投票:0回答: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 的类型以获得更好的性能。

我只是想知道:

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

c++ optimization c++17 compile-time if-constexpr
1个回答
0
投票

您可以在调用

static_assert(HasFastGetData<B>)
之后添加
f
或返回包含结果的
std::pair

方法1

f(obj);
static_assert(HasFastGetData<B>); //this makes sure that the first branch if taken 


方法2

您还可以返回一个

std::pair
(或具有合理命名成员的自定义结构)来检查:

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{} 
    
}

© www.soinside.com 2019 - 2024. All rights reserved.