如何在变元模板之前推导出模板

How to deduce a template before a varidic template

本文关键字:      更新时间:2023-10-16

我目前有以下问题,我的函数模板必须在变量模板之前声明,编译器无法推导它。

template<class F, class... Ts>
void update(F f){
    for(auto t: get_range<Ts...>()){
        apply(std::forward<F>(f), t);
    }
}
..
cg.update<decltype(ftest),int,float>(ftest);
..

有解决这个问题的好办法吗?我想这样称呼它

cg.update<int,float>(ftest);

我相信在C++17中我可以编写

template<class... Ts>
void update(auto f){
    for(auto t: get_range<Ts...>()){
        apply(f, t);
    }
}

但是clang似乎还不支持它。

只需将class F参数放在可变class... Ts参数之后。

template<class... Ts>
void get_range(){ }
auto x = [](auto){};
template<class... Ts, class F>
void update(F f)
{        
    // The following `static_assert` assumes the function is being
    // instantiated with `<int,float>`. It's just here to prove
    // that `F` is not part of `Ts...`.
    // Make sure that `F` is not being caught in `Ts...`:
    static_assert(sizeof...(Ts) == 2, "");
    // Make sure that `F` is actually `decltype(x)`:
    static_assert(std::is_same<decltype(f), decltype(x)>{}, "");
    // Call your function:
    get_range<Ts...>();
}
int main() 
{       
    update<int,float>(x);
    return 0;
}

视频示例

相关文章:
  • 没有找到相关文章