テンプレートを持つ:
template <typename T, template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont=std::vector>
class VehiclesContainer {
public:
VehiclesContainer(std::initializer_list<T> l):container(l){};
virtual ~VehiclesContainer(){};
virtual void addVehicle(T elem);
virtual T getFirst() const;
template
<typename U, template <typename ELEM2, typename ALLOC=std::allocator<ELEM2> > class Cont2>
friend std::ostream& operator<<(std::ostream& out, const VehiclesContainer<U,Cont2>& obj);
private:
Cont<T> container;
};
私は友人クラスとして operator<< を持っています:
template
<typename T,template <typename ELEM,typename ALOC=std::allocator<ELEM> > class Cont>
std::ostream& operator<<(std::ostream& out,const VehiclesContainer<T,Cont>& obj){
typename Cont<T>::const_iterator it;
for(it=obj.container.begin(); it!=obj.container.end(); ++it)
out << *it << " ";
return out;
}
私がやりたいことは、スペースの代わりに-
出力の要素間にある整数のその関数の特殊化を行うことです。私は試した
template
<int,template <typename ELEM,typename ALOC=std::allocator<ELEM> > class Cont>
std::ostream& operator<<(std::ostream& out,const VehiclesContainer<int,Cont>& obj){
typename Cont<int>::const_iterator it;
for(it=obj.container.begin(); it!=obj.container.end(); ++it)
out << *it << "-";
return out;
}
しかし、私がメインでコンパイルするとき
VehiclesContainer<int,std::vector > aStack1({10,20,30});
std::cout << aStack1;
私の特殊化の代わりに、operator<< の一般的な形式が呼び出されます。あまり専門にしていなかったと思います。フレンド クラスの特殊化を宣言する方法はありますか?
WhozCraig の回答に基づく解決策
前方宣言:
template <typename T, template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont=std::vector>
class VehiclesContainer;
template <typename T, template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont>
std::ostream& operator<< (std::ostream& out, const VehiclesContainer<T,Cont>& obj);
template <template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont>
std::ostream& operator<< (std::ostream& out, const VehiclesContainer<int,Cont>& obj);
クラス内の宣言:
friend std::ostream& operator << <T,Cont>(std::ostream&,
const VehiclesContainer<T,Cont>&);
friend std::ostream& operator << <Cont>(std::ostream&,
const VehiclesContainer<int,Cont>&);
フレンド関数の定義:
template <typename T, template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont>
std::ostream& operator <<(std::ostream& os, const VehiclesContainer<T,Cont>& obj)
{
if (obj.container.size() > 0)
{
os << obj.container.front();
for (auto it = std::next(obj.container.begin()); it != obj.container.end(); ++it)
os << ' ' << *it;
}
return os;
}
template <template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class Cont>
std::ostream& operator << (std::ostream& os, const VehiclesContainer<int,Cont>& obj)
{
if (obj.container.size() > 0)
{
os << obj.container.front();
for (auto it = std::next(obj.container.begin()); it != obj.container.end(); ++it)
os << '-' << *it;
}
return os;
}