“模板参数列表太多"专门化成员函数时出错
我想在模板类中定义一些模板成员方法,如下所示:
I would like to define some template member methods inside a template class like so:
template <typename T>
class CallSometing {
public:
void call (T tObj); // 1st
template <typename A>
void call (T tObj, A aObj); // 2nd
template <typename A>
template <typename B>
void call (T tObj, A aObj, B bObj); // 3rd
};
template <typename T> void
CallSometing<T>::call (T tObj) {
std::cout << tObj << ", " << std::endl;
}
template <typename T>
template <typename A> void
CallSometing<T>::call (T tObj, A aObj) {
std::cout << tObj << ", " << aObj << std::endl;
}
template <typename T>
template <typename A>
template <typename B> void
CallSometing<T>::call (T tObj, A aObj, B bObj) {
std::cout << tObj << ", " << aObj << ", " << bObj << ", " << std::endl;
}
但是在实例化模板类的时候,关于三参数的menthod定义有一个错误:
But when instantializing the template class, there is an error concerning the three-argument menthod definition:
CallSometing<int> caller;
caller.call(12); // OK
caller.call(12, 13.0); // OK
caller.call (12, 13.0, std::string("lalala!")); // NOK - complains "error: too many template-parameter-lists"
你能指出我做错了什么吗?为什么第(2)种方法可以,但是第(3种)方法会导致编译时错误?
Could you please point what I am doing wrong? Why the (2nd) method is OK but the (3rd) causes a compile time error?
推荐答案
请阅读 C++ 模板教程,了解如何为模板提供多个参数.而不是
Please read a C++ template tutorial on how to give a template multiple parameters. Instead of
template<typename A> template<typename B> void f(A a, B b);
它的完成方式是
template<typename A, typename B> void f(A a, B b);
多个模板子句代表模板的多个级别(类模板->成员模板).
Multiple template clauses represent multiple levels of templates (class template -> member template).
相关文章