![](/img/trans.png)
[英]Error using auto for return type of specialised template function
[英]Undefined operator error when using specialised template
我正在將最新版本的MSVC與Visual Studio 2015社區版一起使用,並且模板專業化和運算符重載遇到一些問題。
我有以下(僅標頭)向量類代碼段。 我排除了不必要的代碼(即vec2和vec4的相同專長)。
template <typename T, int n>
struct VectorN
{
T data[n];
T& operator[](const int i);
};
template <typename T, int n>
T& VectorN<T, n>::operator[](const int i)
{
static_assert(i >= 0 && i < n, "Index out of range");
return data[i];
}
template <typename T, int n>
std::ostream& operator<<(std::ostream& os, const VectorN<T, n>& vec)
{
for (auto i = 0; i < n; ++i)
{
os << vec[i];
}
return os;
}
具有以下專長:
template <typename T>
struct VectorN<T, 3>
{
union
{
T data[3];
struct
{
T x, y, z;
};
};
};
typedef VectorN<int, 3> Vec3i;
typedef VectorN<float, 3> Vec3f;
我正在編譯的主要功能是:
int main(int argc, char *argv[])
{
Vec3f vec{ 0, 1, 2 };
std::cout << vec << std::endl;
char dump;
std::cin >> dump;
std::cin.clear();
return 0;
}
我希望它能起作用,但是,我得到一個Error: C2676 binary '[': 'const VectorN<float,3>' does not define this operator or a conversion to a type acceptable to the predefined operator
我相信ostream運算符正在按預期工作,但索引運算符卻沒有。 我正在做的任何事情顯然是錯誤的,還是當前的MSVC根本不支持我正在嘗試做的事情?
operator<<
之所以起作用,是因為您對VectorN
模板類型有適當的重載。
另一方面, operator[]
不起作用 ,因為在VectorN
的專用版本中沒有operator[]
(編譯器請告訴您)。
您可以將operator[]
添加到VectorN
類的專用版本,也可以如@DeiDei所述,嘗試將某些功能移至基類。
如果要保留基於union
的解決方案以同時訪問data
和x
, y
, z
的3維向量,則可以使用CTRP創建一個基類,該基類知道派生類的data
成員:
namespace impl
{
template <typename T, int n, typename TDerived>
struct VectorBase
{
const T& operator[](const int i) const
{
assert(i >= 0 && i < n);
return static_cast<const TDerived&>(*this).data[i];
}
};
}
然后可以按以下方式實現派生類:
template <typename T, int n>
struct VectorN : impl::VectorBase<T, n, VectorN<T, n>>
{
T data[n];
};
template <typename T>
struct VectorN<T, 3> : impl::VectorBase<T, 3, VectorN<T, 3>>
{
union
{
T data[3];
struct
{
T x, y, z;
};
};
VectorN(T ax, T ay, T az) : data{ax, ay, az} {}
};
在wandbox上有一個工作示例 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.