简体   繁体   English

C ++中具有非类型参数的部分指定模板类

[英]partial specified template class with nontype parameter in C++

In following code, I got an compiling error 在以下代码中,出现编译错误

#include <iostream>

using namespace std;

template <typename T, int I>
class MyClass {
public:
    void func1(){
    cout<<"default: func1"<<endl;
    }
    void func2(){
    cout<<"default: func2"<<endl;
    }
private:
    T haha;
};

template <typename T>
void MyClass<T, 1>::func1(){
    cout<<"special: func1"<<endl;
};



int main()
{
    MyClass<int, 2> intclass;
    intclass.func1();
    intclass.func2();

    MyClass<double, 1> doubleclass;
    doubleclass.func1();
    doubleclass.func2();
    return 0;
}

I got following compiling error: 我收到以下编译错误:

partialspecifizednontype.cpp:19: error: invalid use of incomplete type 'class MyClass<T, 1>'
partialspecifizednontype.cpp:6: error: declaration of 'class MyClass<T, 1>'

Any specific reason that I can't do this? 我无法执行此操作的任何特定原因? Is there any workaround to achieve this? 有什么解决方法可以做到这一点?

I notice that if my template class don't have first parameter things are OK. 我注意到,如果我的模板类没有第一个参数,则一切正常。 (my gcc is 4.2.1) (我的gcc是4.2.1)

Following example is OK: 以下示例可以:

#include <iostream>

using namespace std;

template <int I>
class MyClass {
public:
    void func1(){
    cout<<"default: func1"<<endl;
    }
    void func2(){
    cout<<"default: func2"<<endl;
    }
};

template<>
void MyClass<1>::func1(){
    cout<<"special: func1"<<endl;
};



int main()
{
    MyClass<2> intclass;
    intclass.func1();
    intclass.func2();

    MyClass<1> doubleclass;
    doubleclass.func1();
    doubleclass.func2();
    return 0;
}

Member functions of class templates are also function templates in their own right. 类模板的成员函数本身也是函数模板。 That means that you can specialize them explicitly (as you do in your second example), but function templates cannot be specialized partially (as you are trying in your first example). 这意味着您可以显式地专门化它们(就像您在第二个示例中所做的那样),但是功能模板不能被部分地专门化(就像您在第一个示例中所尝试的那样)。

As a workaround, you can specialize the entire class partially: 作为一种解决方法,您可以部分专门化整个类:

template <typename T>
class MyClass<T, 1>
{
public:
    void func1() { cout << "special: func1" << endl; };
    // ...
};

You may need to refactor your code to put common code into a base class to make this approach maintainable. 您可能需要重构代码以将通用代码放入基类中,以使此方法可维护。

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

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