C++:运算符和模板

标签 c++ class templates operators operator-overloading

以下是我从另一个问题中获取的示例,我明白为什么这不起作用:

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}

但是,如果我将其更改为以这种方式使用模板:

template <class T>
struct Foo {
    Foo() {}
    Foo(T) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


template <class T>
struct Bar {
    Bar() {}
    Bar(T) {}
};

template <class T>
Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo<int> f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar<int> b;
    b+1;  // DOES NOT WORK
    1+b;  // DOES NOT WORK

}

它不起作用。有人能解释一下吗?模板快把我逼疯了。

谢谢。

最佳答案

有两个问题。

  1. 您需要将模板类型添加到运算符定义中的参数中。这是必要的,因为它需要使用它们来知道要使用哪个 Bar 实例。
  2. 如果您希望在模板函数中使用混合运算符(对两种不同的类型进行操作),则需要提供所有混合情况的定义。否则,模板推演系统将无法按照您想要的方式工作。

.

template <class T>
Bar<T> operator+(Bar<T> const & L, Bar<T> const & R) { // Fixed
    return Bar<T>();
}

template <class T>
Bar<T> operator+(Bar<T> const & L, const T & R) { // Added
    return L + Bar<T>(R);
}


template <class T>
Bar<T> operator+(const T& L, Bar<T> const & R) { // Added
    return Bar<T>(L) + R;
}

关于C++:运算符和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11530151/

相关文章:

c++ - 指向类成员函数的指针

templates - 是否可以将变量传递给 mustache 部分

c# - 使用模板参数调用方法

c++ - 基于成员的集合模板函数

c++ - GNU 如何理解是否设置了标志?

c++ - 有 Arduino PID 代码的说明吗?

c++ - 在 C++ 程序中使用 ASCII 字符

vb.net - 如何使用 LINQ 过滤嵌套类的集合以生成这些类的唯一属性的字典?

php - 将 css li 添加到 php?

c++ - 在 C++ 中使用继承时避免不必要的函数声明/定义