【发布时间】:2015-08-22 11:29:00
【问题描述】:
我想为通用运算符创建一个模板类。该类将有两个结构表示一个值作为输入:
struct Value {
DataType type;
size_t dataSize;
char* data;
};
我已经用 oldschool switch-cases 写了一个类型推导。在将 data-ptr 转换为类型之后,我想对输入值应用如下操作:
template<class Operation>
class ApplyOperation {
Value* operator()(const Value* a, const Value* b) const {
//find type of a and b
//cast a and b to their types
Operation<aT,bT> op;
return op(a,b);
}
};
现在我可以为每个操作编写一个像这样的小结构:
template<class A, class B>
struct Add {
A operator()(A a, B b) const { return a + b; }
};
我见过一个叫做操作符的 boost 类:http://www.boost.org/doc/libs/1_59_0/libs/utility/operators.htm
我想将其用于我的目的。但我不知道如何整合它,因为结构中的运算符不是函子。那么能不能这样用呢?:
ApplyOperation<boost::addable::operator+> add;
add(a,b);
实际上我正在尝试使用此类进行测试:
template<template<class T, class U, class...> class OperatorClass,class F>
struct ApplyOperator {
template<class T, class U>
T foo(T a, U b) {
OperatorClass<T,U> opClass;
return opClass.operator+(a,b); //this works of course
}
};
我想得到的是这样的:
template<template<class T, class U, class...> class OperatorClass,class F>
struct ApplyOperator {
template<class T, class U>
T foo(T a, U b) {
OperatorClass<T,U> opClass;
return opClass.F(a,b);
}
};
这样实例化:
ApplyOperation<boost::addable, operator+> add;
这当然行不通,因为未知类型的 operator+。那么如何用模板调用operator+-function呢?
有没有办法解决这个问题?
【问题讨论】:
-
请张贴minimal reproducible example 说明您要完成的工作