我有以下场景:我有一个结构template<typename CType, int D> struct Point,其中我希望重载操作符< and >。下面是我不确定的问题和要点:我想要不同的< and >实现,这取决于CType是float/double还是int。现在,我正在使用typeinfo中的typid来完成这个操作,但我觉得这不太优雅。我该如何干净利落地做这件事呢?
发布于 2014-08-30 11:52:48
这里有一个选项(使用非会员操作符):
template<typename CType, int D>
bool operator<( Point<CType, D> const &p1, Point<CType, D> const &p2)
{
// generic logic
}
template<int D> bool operator<( Point<float, D> const &p1, Point<float, D> const &p2 )
{
// logic for float
} 可以用float替换enable_if,以生成一个适用于特定类型特征的所有类型的版本(例如,对所有浮点类型都有一个专门化)。
发布于 2014-08-30 11:54:27
现场演示链接。
#include <iostream>
#include <type_traits>
template <typename CType, int D>
struct Point
{
template <typename T = CType>
auto operator<(int t) -> typename std::enable_if<std::is_same<T, int>::value, bool>::type
{
std::cout << "int" << std::endl;
return true;
}
template <typename T = CType>
auto operator<(float t) -> typename std::enable_if<std::is_same<T, float>::value, bool>::type
{
std::cout << "float" << std::endl;
return true;
}
};
int main()
{
Point<int, 1> pi;
Point<float, 1> pf;
pi < 5;
pf < 3.14f;
pi < 3.14f; // forced to apply operator<(int)
}https://stackoverflow.com/questions/25582013
复制相似问题