【发布时间】:2016-04-09 17:53:24
【问题描述】:
为什么下面的代码会产生编译器错误no match for operator*?
template<class E>
class vector_expression {};
template<class Tuple>
class vector
: public vector_expression<vector<Tuple>>
{
public:
using value_type = typename Tuple::value_type;
};
namespace detail
{
template<typename T>
class scalar
: public vector_expression<scalar<T>>
{};
}
template<class E1, class E2, class BinaryOperation>
class vector_binary_operation
: public vector_expression<vector_binary_operation<E1, E2, BinaryOperation>>
{
public:
template<class F1, class F2>
vector_binary_operation(F1&& e1, F2&& e2, BinaryOperation op)
: m_e1(std::forward<F1>(e1)), m_e2(std::forward<F2>(e2)),
m_op(std::move(op))
{ }
private:
E1 m_e1;
E2 m_e2;
BinaryOperation m_op;
};
template<class E>
vector_binary_operation<detail::scalar<typename E::value_type>, E, std::multiplies<>> operator*(typename E::value_type value, E&& e) {
return { std::move(value), std::forward<E>(e), std::multiplies<>{} };
}
template<class E>
vector_binary_operation<E, detail::scalar<typename E::value_type>, std::multiplies<>> operator*(E&& e, typename E::value_type value) {
return { std::forward<E>(e), std::move(value), std::multiplies<>{} };
}
int main()
{
vector<std::array<double, 3>> x;
3 * x;
return 0;
}
【问题讨论】:
-
您的“DEMO”链接对我不起作用。
-
仅供参考,
3是int,而不是double。模板对这类东西很敏感。 -
@MartinBonner 抱歉,已解决。
-
@Cornstalks 这不是重点。如果将
3替换为3.,它仍然不起作用。 -
我想我只需要使用
typename std::decay_t<E>::value_type而不是typename E::value_type。
标签: c++ templates operator-overloading c++14 c++17