模板参数扣除政策

Ale*_*nik 2 c++ templates

我有一个类应该用于将运算符应用于标量或向量以及这些的混合2.该类有效,但我必须手动传递模板参数,而我希望它们从构造函数中扣除.代码如下:

template <template <class,class> class OP, typename Type1, typename Type2>
class BinaryOperator :
    public OP <typename Type1::ReturnType, typename Type2::ReturnType> {
public:

    BinaryOperator(Type1* arg1_, Type2* arg2_) :
        m_arg1(arg1_),
        m_arg2(arg2_) {

    }

    ReturnType evaluate() {
        return this->apply(m_arg1->evaluate(), m_arg2->evaluate());
    }

private:
    Type1* m_arg1;
    Type2* m_arg2;
};
Run Code Online (Sandbox Code Playgroud)

现在,OP是一个具有完整模板专用的结构,用于Scalar/Vector的各种组合,它们是2 ctor参数的ReturnTypes.我必须明确写

new BinaryOperator<op_adder, Axis, Constant>(a1, c2)
Run Code Online (Sandbox Code Playgroud)

虽然我只想写

new BinaryOperator<op_adder>(a1, c2)
Run Code Online (Sandbox Code Playgroud)

并扣除Axis和Constant.编译器错误是:

 too few template arguments for class template 'BinaryOperator'
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?我做错了什么?谢谢亚历克斯

Den*_*ose 5

类类型永远不会推导出模板参数; 毕竟,编译器如何知道哪些构造函数在知道您要创建的类之前要考虑哪些?

解决方案是编写辅助函数ala std::make_pair.

template<typename T, typename U, typename V>
BinaryOperator<T, U, V> make_binary_operator(const U& u, const V& v) {
  return BinaryOperator<T, U, V>(u, v);
}
Run Code Online (Sandbox Code Playgroud)