模板类参数类型的模板类成员的特化
我有一个模板化的类矩阵。我想为复杂类型专门化一个函数,其中 T 可以是任何东西。我已经尝试过:
6 template <typename T>
7 class Matrix {
8 public :
9 static void f();
10 };
11 template<typename T> void Matrix<T>::f() { cout << "generic" << endl; }
12 template<> void Matrix<double>::f() { cout << "double" << endl; }
13 template<typename T> void Matrix<std::complex<T> >::f() { cout << "complex" << endl; }
第 13 行无法编译。我怎样才能做到这一点?
I have a templated class Matrix. I want to specialize a function for the type complex, where T can be anything. I have tried this :
6 template <typename T>
7 class Matrix {
8 public :
9 static void f();
10 };
11 template<typename T> void Matrix<T>::f() { cout << "generic" << endl; }
12 template<> void Matrix<double>::f() { cout << "double" << endl; }
13 template<typename T> void Matrix<std::complex<T> >::f() { cout << "complex" << endl; }
Line 13 does not compile. How can I do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第 11 行和第 12 行中,您对类模板的成员进行了显式特化声明,这是 C++ 标准 14.7/3 所允许的(14.5.2/2 也包含一个很好的示例)。在第 13 行中,您尝试部分特化一个类模板,但这种形式不允许这样做(这是部分特化,因为您不知道整个类型
std::complex
因为它仍然取决于T
)。你应该对整个班级进行部分专业化。In lines 11 and 12 you have declaration of explicit specialization for a member of a class template which is allowed by C++ Standard 14.7/3 (14.5.2/2 contains a good example too). In line 13 you are trying to partially specialize a class template and that is not allowed in this form (this is partial specialization because you don't know the whole type
std::complex<T>
because it is still depends onT
). You should partially specialize the whole class.事实上,我通过 Boost 找到了一个巧妙的方法。由于我不希望我的库依赖于 Boost,因此代码如下:
这样,我可以使用函数重载和模板来实现我的目标。
In fact, I found a clever way to do it through Boost. Since I don't want my library to be dependant on Boost, here is the code :
This way, I can use function overloading and template to achievement my goal.
正如链接答案中所述,您需要做的是专门化整个类,而不是简单的函数:
As describe in the linked answer, what you'll need to do is specialize the entire class, rather than the simple function: