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 的类型以获得更好的性能。我只是想知道:
有没有有效的方法来单元测试我的意图?
您可以在调用
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{}
}