我无法在我的 vec2 模板类中特化一些方法。这是我的代码:
#pragma once
template<typename Number>
struct vec2
{
static_assert(std::is_same<Number, int>::value
|| std::is_same<Number, float>::value
|| std::is_same<Number, double>::value,
"Type not allowed. Use <int>, <float> or <double>.");
Number x, y;
vec2();
vec2(Number x, Number y);
void add(const vec2& other);
inline Number lengthSquared() const;
/*Some other general methods like this two*/
}
我的问题是:我想专门化我的 length
方法如下:
它必须返回 float
如果模板类型是 int
( vec2<int>
)
它必须返回 float
如果模板类型是 float
( vec2<float>
)
它必须返回 double
如果模板类型是 double
(vec2<double>
)
我以前专门研究过我的 length
像这样的方法:
struct vec2
{
/* ... */
inline Number length() const;
}
/*Outside vec2 struct, but in vec2.h*/
template<> inline int vec2<int>::length() const;
template<> inline float vec2<float>::length() const;
template<> inline double vec2<double>::length() const;
然后在我的 .cpp 文件中实现它。这工作正常但它只能返回相同的模板类型,它不能返回 float length
对于 vec2<int>
.有办法吗?
最佳答案
您可以编写一个辅助类型,在给定 vector 组件类型的情况下为您提供 length
的返回类型。
template<typename T>
struct vec_length_t {};
// Specializations:
template<>
struct vec_length_t<int> { using type = float; };
template<>
struct vec_length_t<float> { using type = float; };
template<>
struct vec_length_t<double> { using type = double; };
(或者给它一个更通用的名称以便在其他地方重用,比如 floatify
或类似的)
然后像这样使用它:
template<typename Number>
struct vec2 {
...
typename vec_length_t<Number>::type length() const;
...
};
要在同一个类中被多个函数复用或使用,当然也可以使用本地类型别名:
template<typename Number>
struct vec2 {
...
using length_t = typename vec_length_t<Number>::type;
...
length_t length() const;
...
};
这使得在函数体中使用 length_t
来调用正确的 std::sqrt
重载变得容易(您可能不想使用 double
当你要返回一个float
时重载!):
template<typename Number>
vec2<Number>::length_t vec2<Number>::length() const {
// Note that x*x+y*y is a Number, but we want a length_t:
return std::sqrt(static_cast<length_t>(x*x + y*y));
// Or, if you have lengthSquared() defined as returning a Number:
return std::sqrt(static_cast<length_t>(lengthSquared()));
}
关于c++ - 仅针对某些方法的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403452/