2014-08-30 18 views
1

我有以下情形:我有一個結構template<typename CType, int D> struct Point,其中我想重載運算符<和>。這裏出現的問題和我不確定的觀點:我需要<和>的不同實現,具體取決於CType是float/double還是int。現在我正在使用typeinfo中的typid來做這件事,但我覺得這樣不夠高雅。我如何以乾淨的方式去做這件事?模板中的重載運算符結構

回答

2

這裏是一個選項(使用非成員操作符):

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做,對於所有類型的某種類型特徵的工作的版本(例如已針對所有浮點類型的單一專業化)。

1

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