【问题标题】:template method specialisation problem模板方法特化问题
【发布时间】:2011-03-25 21:15:37
【问题描述】:

谁能帮我处理这段代码。我正在尝试专门研究一种方法。目前它不适用于一个专业(1),但我希望最终有很多专业(2、3、4、5等)

class X
{
public:

    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length );

    // specialisations

    template<> void set_native< 1 >( char *ptr, unsigned int length )
    {
    }

};

我收到的错误消息是..

x.cpp:13:错误:非命名空间范围“X 类”中的显式特化 x.cpp:13: 错误: 'void set_native(char*, unsigned int)' 的模板 ID 'set_native' 与任何模板声明都不匹配 x.cpp:13: 错误:无效的函数声明

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    试试下面的

    class X
    {
    public:
    
        // declaration
        template< int FLD >
        void set_native( char *ptr, unsigned int length );
    };
    
    // specialisations
    template<> void X::set_native< 1 >( char *ptr, unsigned int length )
    {
    }
    

    如果不起作用,请尝试在 set_native 后面添加模板类

    template<int FLD> class SetNative;
    class X
    {
    public:    
        // declaration
        template< int FLD >
        void set_native( char *ptr, unsigned int length )
        { return SetNative()(ptr, length); }
    };
    template<> class SetNative<1>
    {
      void operator()( char *ptr, unsigned int length ){...}
    };
    

    【讨论】:

    • 方法 #2 不是必需的,第一种方法是合规的并且 (afaik) 完全可移植。
    【解决方案2】:

    正如 Benoit 所建议的,您必须在周围的命名空间中专门化成员函数:

    struct X {
        template<int N> void f() {}
    };
    
    template<> void X::f<1>() {} // explicit specialization at namespace scope
    

    这是因为 §14.7.3 (C++03):

    应在模板所属的命名空间中声明显式特化,或者,对于成员模板,应在封闭类或封闭类模板所属的命名空间中声明。

    然而,VC 在这方面不符合标准,因此造成了一些可移植性问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2012-08-13
      相关资源
      最近更新 更多