【问题标题】:C++, template specialization problemC++,模板特化问题
【发布时间】:2011-05-06 20:47:43
【问题描述】:

我在模板类专业化方面遇到问题,请参阅下面的代码。

template <typename T>
class Point
{
    private
            T x, y;
            typedef T Type;

    public:

            Point ( const T & x_, const T & y_) : x ( x_ ), y ( y_ ) {}
};

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


template <typename Item>
class Container
{
    protected:
            typename TItems <Item>::Type items;

    public:
            typedef Item type;
};   

是否可以为 Point 专门化 Container 类?

更新问题:

我试过下面的代码,有效吗?

template <typename T>
class Container < Point <T>  >
{

};

int _tmain(int argc, _TCHAR* argv[])
{
return 0;

Container <Point <double> > points;
}

【问题讨论】:

    标签: c++ templates specialization


    【解决方案1】:

    你可以,是的,但你的语法不太正确。就目前而言,编译器不知道T 是什么,所以你必须告诉它它是一个模板参数:

     template<typename T>
     class Container<Point<T> > { };
    

    【讨论】:

    • 谢谢,我在您发布答案的同时更正了我的代码:-)
    【解决方案2】:

    是的,您可以使用 Point &lt;T&gt; 类型专门化您的课程。

    编辑:

    我试过下面的代码,是不是 有效吗?

    如果你试过下面的代码,你不知道它是否编译了吗? 0_o

    int _tmain(int argc, _TCHAR* argv[])
    {
    Container <Point <double> > points;
    return 0; // return should be here nor program will exit before creating Container <Point <double> > points;
    }
    

    r

    【讨论】:

    • _tmain 不是一个合法的函数名,所以它编译的事实并不能真正为代码是否合法提供太多帮助。
    • 我认为他正在使用 Visual Studio。
    • @Dennis,_tmain 怎么不是合法的函数名?这是一个有效的标识符,甚至不是一个保留的标识符。
    • @Ben:在全局范围内,保留以下划线开头的名称。重要的是,简单地编译代码暗示了准确性,但并不能保证准确性。
    • @Dennis:为实现保留,该实现指定它是一个扩展为入口点名称(mainwmain)的宏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多