问题描述
我对类模板中的内部类有疑问。我有一个模板类(例如: Matrix< T>
)和一个子类(例如: Matrix< T> :: Row
)。现在,我想编写一个对子类实例进行操作的函数(例如: negate(Matrix< T> :: Row&)
)。我试图用 template< class T>声明函数。 negate(typename Matrix< T> :: Row&)
,但是当我尝试使用它时,编译器告诉我找不到匹配项。
I have a problem with inner classes in class templates. I have a template class (say: Matrix<T>
), and a subclass (say: Matrix<T>::Row
). Now I want to to write a function which operates on instances of the subclass (say: negate(Matrix<T>::Row &)
). I tried to declare the function with template<class T> negate(typename Matrix<T>::Row &)
, but when I try to use it, the compiler tells me that it cannot find a match.
这是一个抽象示例:
template<class T>
class A
{
public:
class B
{
};
};
template<class T>
void x(typename A<T>::B &)
{
}
int main()
{
A<int>::B b;
x(b); // doesn't work: Error: Could not find a match
// for x<T>(A<int>::B) needed in main().
x<int>(b); // works fine
}
为什么编译器无法找到 x
在第一种情况下?有没有办法修改它的工作原理(无需显式指定类型 int
)?
Why does the compiler does not manage to find x
in the first case? Is there a way to modify this that it works (without explicitly specifying the type int
)?
(我也遇到类似的问题,其中 x
的形式为 template< class T ,类S> void x(typename A< T> :: B& ;, const S&);
,我真的不想在执行调用时被迫显式命名所有类型。)
(I also have similar problems where x
is of the form template<class T, class S> void x(typename A<T>::B &, const S &);
, whence I would really like not to be forced to explicitly name all types while doing the call.)
我已经使用g ++ 4.4.3,g ++ 4.5.2和Sun Studio 5.9尝试了全部相同的结果。
I have tried this with g++ 4.4.3, g++ 4.5.2, and Sun Studio 5.9, all give the same result. Thanks a lot in advance for anything helpful!
推荐答案
编译器应如何推断呢?想象以下设置:
How should the compiler be able to deduce this? Imagine the following setup:
struct A { typedef int T; };
struct B { typedef int T; };
template <typename S> void foo(typename S::T);
现在,当您说 int x; foo(x);
,没有明确的匹配方法。
Now when you say int x; foo(x);
, there's no way to match this unambiguously.
要点是,您不是从给定值中推导出模板参数类模板,而是一个任意的独立类型。该类型在另一个类中定义的事实与此无关。
The point is that you are not deducing a template parameter from a given class template, but rather just an arbitrary, free-standing type. The fact that that type was defined inside another class is not relevant for that.
这篇关于函数接受模板类的内部类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!