【问题标题】:Can I use boost operators to generate comparision functions for 2 objects(with different types) of class?我可以使用 boost 运算符为类的 2 个对象(具有不同类型)生成比较函数吗?
【发布时间】:2011-11-23 23:06:25
【问题描述】:

我想用boost operators这样的方式生成比较函数:

template <typename T>
class Foo : boost::less_than_comparable<Foo<T>, Foo<T2> > {
    private:
        int bar;
    public:
        template <typename T2>
        friend bool operator<(Foo<T> const& f1, Foo<T2> const& f2) {
            if (typeid(T) == typeid(T2)) {
                return f1.bar < f2.bar;
            } else {
                return sizeof(T) < sizeof(T2);
            }
        }
};

有可能吗?如果我们可以以某种方式使用 boost 运算符来生成其余的运算符,那么运算符实际上并不需要成为朋友。

【问题讨论】:

    标签: c++ templates boost


    【解决方案1】:

    您可能应该只使用重载的函数模板:

    template <typename T>
    bool operator<(Foo<T> const& f1, Foo<T> const& f2) {
        return f1.bar < f2.bar;
    }
    
    template <typename T1, typename T2>
    bool operator<(Foo<T1> const& f1, Foo<T2> const& f2) {
        return sizeof(T1) < sizeof(T2);
    }
    

    【讨论】:

    • 感谢您的回答,但我的主要问题是class Foo : boost::less_than_comparable&lt;Foo&lt;T&gt;, Foo&lt;T2&gt; &gt; { 行,因为那里没有声明 T2。
    • @vintitres :是的,这不是可以干净地解决的问题。这个答案显示了干净的方法。
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 2015-06-30
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多