mat*_*ort 4 c++ templates c++14
下面的代码编译并按照我想要的方式使用clang和gcc,但在Visual Studio 2015 RTM中出错.我认为clang和gcc是正确的,但我不确定.这段代码应该编译吗?
#include <iostream>
#include <type_traits>
#include <utility>
template <typename T, size_t N, typename IS = decltype(std::make_index_sequence<N>{})>
struct Vector {
T e_[N];
};
template <typename T, typename U, size_t N, size_t... Is>
constexpr auto operator+(const Vector<T, N, std::index_sequence<Is...>>& x,
const Vector<U, N>& y) {
using V = std::common_type_t<T, U>;
return Vector<V, N>{x.e_[Is] + y.e_[Is]...};
}
int main() {
const auto v0 = Vector<float, 4>{1, 2, 3, 4};
const auto v1 = Vector<float, 4>{5, 6, 7, 8};
const auto v2 = v0 + v1;
for (auto x : v2.e_) std::cout << x << ", ";
std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果我将operator +更改为:Visual Studio将编译为ok:
template <typename T, typename U, size_t N, size_t... Is>
constexpr auto operator+(const Vector<T, N, std::index_sequence<Is...>>& x,
const Vector<U, N, std::index_sequence<Is...>>& y);
Run Code Online (Sandbox Code Playgroud)
但我认为没有必要std::index_sequence<Is...>再次提出y.
IS不应该是这种类型的一部分Vector.相反,使用辅助函数:
template <typename T, std::size_t N>
struct Vector {
T e_[N];
};
template <typename T, typename U, std::size_t N, std::size_t... Is>
inline constexpr auto add_impl(const Vector<T, N>& x, const Vector<U, N>& y,
std::index_sequence<Is...>) {
using V = std::common_type_t<T, U>;
return Vector<V, N>{x.e_[Is] + y.e_[Is]...};
}
template <typename T, typename U, std::size_t N,
typename Is = std::make_index_sequence<N>>
constexpr auto operator+(const Vector<T, N>& x, const Vector<U, N>& y) {
return add_impl(x, y, Is());
}
Run Code Online (Sandbox Code Playgroud)
我无法访问VS2015来测试它,但它应该可以工作.
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |