【问题标题】:C++, templates with default parametersC++,带有默认参数的模板
【发布时间】:2011-08-27 02:57:33
【问题描述】:

一个简化的例子:

有一个抽象模板类 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";
}

【问题讨论】:

  • 我建议的第一件事是大量将此处发生的代码量减少到引发错误所需的最少。跨度>
  • 您应该在这个问题中修剪代码,这样我们就不必仔细阅读所有这些了。另外,请参阅我的回答,您没有向我们提供 真正使用的正确代码。

标签: c++ templates default-value


【解决方案1】:

你的代码对我来说编译得很好,你没有给我们你真正拥有的代码。除此之外,您的问题似乎是您想提供错误的输入。您的 test 函数需要一个指向点的容器 (Cont&lt; Point&lt;T&gt;* &gt;),但您提供了一个点容器 (Cont&lt; Point&lt;T&gt; &gt;):

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

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

Cont< Point<int>* >* pc;

即一个指针容器。您在问题中正确执行了此操作,但您的真实代码似乎并非如此。

【讨论】:

  • 很抱歉,这段代码在 VS 2010 上无法编译...我不创建点容器,而是创建指向点的指针容器,请参阅 main()。这两个函数都有指向容器的指针,指向作为形式参数的点,请再次查看代码...I
  • @Johny:正如我所说,你给出的例子对我来说编译得很好。
  • @Johny:VS2010,启用语言扩展和警告级别 4。
猜你喜欢
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2015-05-09
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多