开发者

Template parameters deduction with policies

开发者 https://www.devze.com 2023-04-11 14:52 出处:网络
I have a class that is supposed to be used to apply operators to scalars or vectors and a mix of these 2. The class works, but I have to manually pass the template parameters, while I would like them

I have a class that is supposed to be used to apply operators to scalars or vectors and a mix of these 2. The class works, but I have to manually pass the template parameters, while I would like them to be deducted from the constructor. The code is the following:

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

privat开发者_StackOverflowe:
    Type1* m_arg1;
    Type2* m_arg2;
};

Now, the OP is a structure with full template specialization for the various combinations of Scalar/Vector that are the ReturnTypes of the 2 ctor parameters. I have to write explicitly

new BinaryOperator<op_adder, Axis, Constant>(a1, c2)

while I'd just like to write

new BinaryOperator<op_adder>(a1, c2)

and have Axis and Constant deducted. The compiler error is:

 too few template arguments for class template 'BinaryOperator'

Can some one help? What I am doing wrong? Thanks alex


Class types can never have template arguments deduced; after all, how can the compiler know which constructors to consider before it even knows what class you are trying to create?

The solution is to write a helper function, 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消