如何在varidic模板之前推导出模板

时间:2015-11-22 23:31:37

标签: c++ c++14 c++17

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

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似乎还没有支持它。

1 个答案:

答案 0 :(得分:6)

只需将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;
}

ideone example