C++,具有默认参数的模板

C++, templates with default parameters

本文关键字:参数 默认 C++      更新时间:2023-10-16

一个简化的例子:

有一个抽象模板类GCont表示一个通用容器

template <typename Item>
struct TList
{
    typedef std::vector <Item> Type;
};

template <typename Item>
class GCont
{
    protected:
            typename TList <Item>::Type items;
    public:
            typedef Item type;
            virtual ~GCont() = 0 {};
};

和派生的抽象模板类,具有一个隐式参数

template < typename Item, const bool par = true>
class GCont2 : public GCont <Item>
{
    public:
            GCont2 () : GCont <Item> () {}
    virtual ~GCont2() = 0 {};
};

及其对指针的专门化

template <typename Item, const bool par>
class GCont2 <Item *, par> : public GCont <Item *>
{
    public:
            GCont2 () : GCont <Item *> () {}
            virtual ~Cont() {}
};

派生的模板类 Cont

template <typename Point, const bool par = true>
class Cont : public GCont2 <Point, par>
{
    public:
            Cont() : GCont2 <Point, par>() {}
            virtual ~Cont() {}
};

和指针的专用化

template <typename Point, const bool par>
class Cont <Point *, par> : public GCont2 <Point *, par>
{
    public:
            Cont() : GCont2 <Point *, par> () {}
};

类点:

template <typename T>
class Point
{
    protected:
            T x, y, z;
};

是否可以编写一个具有通用形式参数的函数 test() 来分配同时使用两者

Cont <Point <T> *> *points

Cont <Point <T> *, false> *points

在我的程序中

template <typename T>
void test (Cont <Point <T> *> *points)
{
std::cout << "test";
}
template <typename T>
void test2 (Cont <Point <T> *, false> *points)
{
std::cout << "test2";
}
int _tmain(int argc, _TCHAR* argv[])
{
Point <double> * p = new Point <double>();
Cont <Point <double> *, false> points;
    test(&points); //Error
     test2(&points); //OK
return 0;
}

在转换过程中,出现以下错误:

Error   1   error C2784: 'void test(Cont<Point<T>*> *)' : could not deduce template argument for 'Cont<Point<T>*> *' from 'Cont<Point,par> *'   g:templates_example.cpp    27

感谢您的帮助...

更新状态

我修剪了代码...但问题仍然存在...我的代码在使用 MSVS 2010 时无法编译相同的错误。

我找到了容器的部分解决方案模板化。

template <typename Container>
void test (Container *points)
{
std::cout << "test";
}

你的代码对我来说完全没问题,你没有给我们你真正拥有的代码。除此之外,您的问题似乎是您想提供错误的输入。您的test函数需要一个指向点的指针容器(Cont< Point<T>* >),但您提供了一个点的容器(Cont< Point<T> >):

Cont< Point<int> >* pc;
// ...
test(pc);

这当然会产生您得到的错误。你需要一个

Cont< Point<int>* >* pc;

也就是说,指针的容器。你在问题中正确地这样做了,但你的真实代码似乎并非如此。