2

我一直在寻找与我的问题有关的示例,但我仍然找不到解决方案。我发现的最接近的是

模板函数作为模板参数

如果需要,我将尝试发布一个工作示例,但到目前为止,我的部分代码涉及以下内容:

template<class InterfaceType, class T> 
inline void write_info(InterfaceType& interface, T& t) {
    InterfaceType::write_info(interface, t);
}

template<class InterfaceType, class T> 
inline void write_data(InterfaceType& interface, T& t) {
    InterfaceType::write_data(interface, t);
}

template<class InterfaceType, class T> 
inline void write_definition(InterfaceType& interface, T& t) {
    InterfaceType::write_definition(interface, t);
}

请注意,模板write_info依赖于接口类型,该接口类型具有称为write_info(静态方法)的方法。这样做的原因是因为该write_info函数稍后可以针对特定数据类型进行专门化,而无需在InterfaceType.

一个简单的问题是:我们可以用一个将函数命名为函数参数的模板来简化上面的代码吗?请记住,我真的希望这成为可能,这样我就可以避免为专门的数据类型定义所有这 3 个函数,即

假设这foo是一个具有两个属性int a和的结构double b。然后我可以像这样专门化上述功能:

template<class InterfaceType> 
inline void write_info(InterfaceType& interface, foo& t) {
    InterfaceType::write_info(interface, t.a);
    InterfaceType::write_info(interface, t.b);
}

template<class InterfaceType> 
inline void write_data(InterfaceType& interface, foo& t) {
    InterfaceType::write_data(interface, t.a);
    InterfaceType::write_data(interface, t.b);
}

template<class InterfaceType> 
inline void write_definition(InterfaceType& interface, foo& t) {
    InterfaceType::write_definition(interface, t.a);
    InterfaceType::write_definition(interface, t.b);
}

如您所见,我一遍又一遍地编写相同的代码。在这里,我假设 InterfaceType 已经有 define write_info、forwrite_data和。有任何想法吗?write_definitionintdouble

4

1 回答 1

5

扭转逻辑:与其write_thing为每种类型编写专门的重载,不如编写一个apply函数,将任意函数应用于每种类型的对象,然后将每个函数的单个重载write_thing简单地委托给apply

// Define a catch-all apply that handles "everything else"
template <typename Interface, typename Function, typename Object>
void apply(Interface& i, Function f, Object& x) {
    f(i, x);
}

// Define overloads for "apply" that handle special cases
template <typename Interface, typename Function>
void apply(Interface& i, Function f, foo& x) {
    f(i, x.a);
    f(i, x.b);
}

// Define polymorphic adapters for your write_[thing] functions:
struct write_info_impl {
    template <typename Interface, typename Object>
    void operator()(Interface& i, Object& x) const {
        Interface::write_info(i, x);
    }
};

// Then implement your write_[thing] functions in terms of the above:
template <typename Interface, typename Object>
void write_info(Interface& interface, Object& x) {
    apply(i, write_info_impl(), x);
}
于 2012-09-26T17:36:26.240 回答