简体   繁体   English

非类型模板类成员专业化

[英]Nontype template class member specialization

Consider the following c++ code: 考虑以下c ++代码:

template <int K>
struct KData
{
   float data[K];
};

template<int K>
class KClass
{
public:   
    typedef KData<K> Data;
    Data m_data;

    Data square()
    {
        Data result;
        for(int i = 0; i < K; ++i)
            result.data[i] = m_data.data[i] * m_data.data[i];
        return result;
    }

    // Specialization for K = 2
    template<>
    KClass<2>::Data square();
};

template<>
KClass<2>::Data KClass<2>::square()
{
   Data result;
   result.data[0] = m_data.data[0] * m_data.data[0];
   result.data[1] = m_data.data[1] * m_data.data[1];
   return result;
}

int main()
{
   KClass<2> c;
   c.m_data.data[0] = c.m_data.data[1] = 1.f;
   c.square();

   return 0;
}

It has a the 'KCalss' which has a template data member ('m_data') and a method that performs some computations on that data member ('square()'). 它有一个带有模板数据成员('m_data')的'KCalss'和对该数据成员执行一些计算的方法('square()')。 What I want to do is to make an specialization of 'square()' for the case when K = 2, for example. 我想做的是对例如K = 2的情况进行'square()'的特殊化处理。

Trying to compile it with 4.6.7 or 4.7.2 gives the following error: 尝试使用4.6.7或4.7.2进行编译会产生以下错误:

main.cpp:23:14: error: explicit specialization in non-namespace scope 'class KClass' main.cpp:23:14:错误:非命名空间范围'class KClass'中的显式专门化

main.cpp:24:5: error: 'Data' in 'class KClass<2>' does not name a type main.cpp:24:5:错误:``类KClass <2>''中的``数据''未命名类型

Any idea of what I'm doing wrong? 有什么想法我做错了吗?

Thanks in advance. 提前致谢。

=== EDIT === ===编辑===

A workaround I found is to declare the second 'square()' method as a template as well: 我发现的一种解决方法是也将第二个“ square()”方法声明为模板:

template<int K2>
typename KClass<K2>::Data square();

It works nicely, but it allows the user to call 'aquare()' passing a template parameter different from the class, eg: 它工作得很好,但是它允许用户通过传递不同于类的模板参数来调用“ aquare()”,例如:

KClass<2> c;
c.square<3>;

which gives a "undefined reference to" linking error. 给出“未定义的引用”链接错误。

=== EDIT (SOLUTION) === ===编辑(解决方案)===

All right, the solution was simpler than I expected. 好的,解决方案比我预期的要简单。 I just had to remove the template declaration: 我只需要删除模板声明:

template<>
inline KClass<2>::Data square();

, which is unnecessary. ,这是不必要的。

template<>
KClass<2>::Data KClass<2>::square()
                ^^^^^^^^
{

And you have to remove this. 而且您必须删除它。 This is not how you specialize a member function. 这不是您专门化成员函数的方式。 The member function can not be specialized with in the class scope. 成员函数不能在类范围内专用。 It needs to be specialized within the surrounding namespace of the class declaration. 它需要在类声明的周围名称空间内进行专门化。

 template<>
 KClass<2>::Data square();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM