【问题标题】:Function of a templated class as template parameter模板化类作为模板参数的功能
【发布时间】: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呢?

有没有办法解决这个问题?

【问题讨论】:

标签: c++ templates boost


【解决方案1】:

我不确定我是否完全理解了这个问题。但看起来您正在尝试为模板 ApplyOperator 提供对象实例(而不是类型)。由于 operator+ 绝对不是类型,也不是整数常量,所以它绝对不能用作模板参数。您需要做的是将操作作为构造函数的参数,而不是对象的类型。

【讨论】:

  • 有没有办法通过模板告诉使用哪个成员函数?
  • 没有。唯一可以作为模板参数的两件事是类型或整数常量。函数指针都不是。
猜你喜欢
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
相关资源
最近更新 更多