Мак*_*ков 5 c++ templates variadic-templates c++17
这是连接元组的二元运算符:
template <class... Args1, class... Args2>
constexpr decltype(auto) operator+(const std::tuple<Args1...> &tup1,
const std::tuple<Args2...> &tup2) {
return std::tuple_cat(tup1, tup2);
}
Run Code Online (Sandbox Code Playgroud)
它在两个元组的编译器(gcc,clang)上都能很好地工作:
template <class Arg1, class Arg2>
constexpr decltype(auto) concat_test(Arg1 &&arg1, Arg2 &&arg2) {
return arg1 + arg2;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在折叠表达式中使用它时,如下所示:
template <class... Args>
constexpr decltype(auto) multiple_concat(Args &&... args) {
return (args + ...);
}
Run Code Online (Sandbox Code Playgroud)
gcc 7.1.1编译它没有任何错误,不像clang 5.0,它产生错误输出:
error:调用函数'operator +',它在模板定义中既不可见,也不能由参数依赖查找找到
return(args + ...);
注意:在实例化函数模板特化'multiple_concat <std :: __ 1 :: tuple&,std :: __ 1 :: tuple&>'这里请求
multiple_concat(tup1,tup2);
注意:'operator +'应在呼叫站点之前声明
constexpr decltype(auto)operator +(const std :: tuple&tup1,const std :: tuple&tup2)
这段代码是不正确的,究竟是什么铿锵谈论的?
2018 年 8 月:Xcode 9.0(大致相当于开源 clang 4.0)仍然无法编译此代码,而 g++ 可以正确完成该工作。
我知道无法使用闪亮的新模板折叠语法是很痛苦的,但这里有一个基于 的解决方法if constexpr,这是我们可以使用的下一个最好的方法。
template <typename T, typename... Ts>
constexpr decltype(auto) multiple_concat(T&& arg, Ts&&... rest) {
if constexpr (sizeof ...(rest) == 0) {
return arg;
}
else { // recursively concatenate the tuple
return arg + multiple_concat(std::forward<Ts>(rest) ...);
}
}
Run Code Online (Sandbox Code Playgroud)
Clang 愉快地编译了这段代码。
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |