gpt4 book ai didi

c++ - 模板方法特化问题

转载 作者:行者123 更新时间:2023-11-30 04:38:01 26 4
gpt4 key购买 nike

任何人都可以帮我处理这段代码。我正在尝试专门化一种方法。目前它不适用于一种特化 (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<1>' 与任何模板声明都不匹配x.cpp:13: 错误:函数声明无效

最佳答案

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

struct X {
template<int N> void f() {}
};

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

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

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.

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

关于c++ - 模板方法特化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3416339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com