我有一个表示数学 vector 的类模板:
template<class Value_T, unsigned int N>
class VectorT
{
public:
void Normalize()
{
// normalize only double/float vectors here
}
private:
// elements in the vector
value_type elements[N];
// the number of elements
static const size_type size = N;
};
我想对整数类型的 vector 进行特殊处理,因为这种类型的 vector 规范化是不可能的。所以我需要一个单独的(可能是专门化的)Normalize 方法,它依赖于 VectorT 类模板的模板参数 Value_T。
我曾尝试以不同的方式使用模板特化,但没有成功。我是否必须使 Normalize 函数本身成为模板函数?目前它只是一个普通成员方法。
最佳答案
您可以使用标签调度技术解决这个问题:
#include <iostream>
#include <type_traits>
template<class Value_T, unsigned int N>
class VectorT
{
public:
void Normalize()
{
using tag = std::integral_constant<bool
, std::is_same<Value_T, double>::value
|| std::is_same<Value_T, float>::value>;
// normalize only double/float vectors here
Normalize(tag());
}
private:
void Normalize(std::true_type)
{
std::cout << "Normalizing" << std::endl;
}
void Normalize(std::false_type)
{
std::cout << "Not normalizing" << std::endl;
}
// elements in the vector
Value_T elements[N];
// the number of elements
static const std::size_t size = N;
};
关于C++ - 为模板类专门化成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260774/