简体   繁体   English

模板结构中的重载运算符

[英]Overload operator in template struct

I have the following scenario: I have a struct template<typename CType, int D> struct Point in which I want to overload the operators < and >. 我有以下场景:我有一个结构template<typename CType, int D> struct Point我要重载运算符<和>。 Here comes the catch and the point I am not sure about: I want different implementations of < and > depending on if CType is float/double or int. 接下来是我不确定的问题:我想要<和>的不同实现,具体取决于CType是float还是double还是int。 Right now I'm doing this using typid from typeinfo, but I feel like this is not elegant. 现在我正在使用typeinfo中的typid来做这件事,但我觉得这不优雅。 How do I go about doing this in a clean way? 我该如何以干净的方式做到这一点?

Here is one option (using non-member operators): 这是一个选项(使用非成员运算符):

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
} 

It might be possible to replace float with an enable_if to make a version that works for all types of a certain type trait (eg have a single specialization for all floating point types). 可以使用enable_if替换float以生成适用于特定类型特征的所有类型的版本(例如,对所有浮点类型具有单一特化)。

Live demo link. 现场演示链接。

#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) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM