2014-04-17 33 views
1

我在C++高度模板代码和代码工作是推动我疯了,因为我经常要惹这样的可憎各地:C++如何使模板代码更加清晰

std::pair<typename P<A, B>::const iterator, std::pair<long, typename P<A, B>::const_iterator> p; 

(没有C++ 11元组)

这:

template <A, B, C, D, E> 
class MyClass { 
    private: 
    P <A, B> p; 
    Q <C, D> q; 
    // (does nothing with A, B, C, D but has to use the template because 
    // this class uses other templated classes P<A, B> and Q<C, D>) 
    // ... 
}; 

有没有一种方法,使代码更清洁,更具有可读性喜欢使用typedef或其他的技巧?

编辑: 认为P和Q为std :: maps,我不知道类型。

这里是〜我的代码是如何工作的

template<A, B, C, D> 
class MapWrapper { 
    private: 
    std::map< map<A, B>::const_iterator, map<C, D>::const_iterator > _map; 

    public: 
    void insert_in_map (map<A, B>::const_iterator one, map<C, D>::const_iterator two) { 
     _map[one] = two; 
    } 
}; 
+5

是的,用'typedef'或'using'。但你已经说过,在这个问题上,所以我不确定你在找什么...... –

+0

我如何使用typedef来减少模板?我不能使用,因为模板的一个副作用是我必须把所有代码放在.h –

+1

您的问题中的长表达式std :: pair <...'是无效的... – Danvil

回答

2

一种选择就是把它重写

template <class P, class Q> 
class MyClass { 
    private: 
    P p; 
    Q q; 
}; 

,而是使用类似

MyClass<A, B, C, D, E> 

他们改变

MyClass<P<A, B>, Q<C, D>> 

这样,正确使用typedefs,可能减少样板量。

另一种选择是通过应用某种类型的擦除(即使用较少的模板)来支付运行时性能。

编辑:下你的编辑,在具体的代码,你可以概括你的类与任何对迭代器的工作:

template<class I1, class I2> 
class MapWrapper { 
    private: 
    std::map<I1, I2> _map; 

    public: 
    void insert_in_map (I1 one, I2 two) { 
     _map[one] = two; 
    } 
}; 

根据不同的算法部分,这可能会或可能不会,合理。

+0

可以随时添加另一个“模板类MyOtherClass”,它是MyClass 的同义词,Q >'。 – Sjoerd

+0

但是,我只是将模板责任转移给使用我的代码的人。 –

+0

现在我想起来了,模板化这个类并不是模板化后的东西。 –