请允许我考虑以下合成示例:
inline int fun2(int x) {
return x;
}
inline int fun2(double x) {
return 0;
}
inline int fun2(float x) {
return -1;
}
int fun(const std::tuple<int,double,float>& t, std::size_t i) {
switch(i) {
case 0: return fun2(std::get<0>(t));
case 1: return fun2(std::get<1>(t));
case 2: return fun2(std::get<2>(t));
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我应该如何将其扩展到一般情况
template<class... Args> int fun(const std::tuple<Args...>& t, std::size_t i) {
// ?
}
Run Code Online (Sandbox Code Playgroud)
保证这一点
众所周知,当足够大的交换机扩展时,优化器通常使用查找跳转表或编译时二进制搜索树.所以,我想保持这个属性影响大量项目的性能.
更新#3:我使用统一随机索引值重新测量性能:
1 10 20 100
@TartanLlama
gcc ~0 42.9235 44.7900 46.5233
clang 10.2046 38.7656 …Run Code Online (Sandbox Code Playgroud) 使用std::visit/ std::variant我在分析器输出中看到std::__detail::__variant::__gen_vtable_impl函数占用的时间最多.
我做了这样的测试:
// 3 class families, all like this
class ElementDerivedN: public ElementBase
{
...
std::variant<ElementDerived1*, ElementDerived2*,... > GetVariant() override { return this; }
}
std::vector<Element*> elements;
std::vector<Visitor*> visitors;
std::vector<Third*> thirds;
// prepare a hack to get dynamic function object:
template<class... Ts> struct funcs : Ts... { using Ts::operator()...; };
template<class... Ts> funcs(Ts...) -> funcs<Ts...>;
// demo functions:
struct Actions { template < typename R, typename S, typename T> void operator()( R*, S*, T* …Run Code Online (Sandbox Code Playgroud)