下面的代码编译并按照我想要的方式使用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;
}
如果我将operator +更改为:
,Visual Studio会编译好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);
但我不认为有必要再次为std::index_sequence<Is...>
添加y
。
答案 0 :(得分:6)
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());
}
我无法访问VS2015进行测试,但它应该有效。