簡體   English   中英

模板結構中的重載運算符

[英]Overload operator in template struct

我有以下場景:我有一個結構template<typename CType, int D> struct Point我要重載運算符<和>。 接下來是我不確定的問題:我想要<和>的不同實現,具體取決於CType是float還是double還是int。 現在我正在使用typeinfo中的typid來做這件事,但我覺得這不優雅。 我該如何以干凈的方式做到這一點?

這是一個選項(使用非成員運算符):

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
} 

可以使用enable_if替換float以生成適用於特定類型特征的所有類型的版本(例如,對所有浮點類型具有單一特化)。

現場演示鏈接。

#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