我正在尝试构建一个模板化的 C++ 函数,它接受一个指向内部类对象的指针作为其参数。这是所涉及的类结构的简化版本,类似于典型的链表或树类:
template <typename T>
struct Outer
{
struct Inner
{
T val;
Inner (T v) : val(v) { }
};
Inner* ptr;
Outer(T val)
{
ptr = new Inner(val);
}
};
我已经将它们构造为排除任何访问控制问题并删除了一些无关的实例变量。考虑到该类结构,这里有三个函数,其中前两个不是我想要的:
template <typename T>
void testOuter (const Outer<T>& obj)
{
cout << obj.ptr->val << endl;
}
void testInnerInt (const Outer<int>::Inner* p)
{
cout << p->val << endl;
}
template <typename T>
void testInnerTemplated (const typename Outer<T>::Inner* p)
{
cout << p->val << endl;
}
这第三个函数基本上是我想要的,在 header 方面(当然,它旨在作为更大代码体中的辅助函数),但它不起作用。如果我编译并运行以下主要函数:
int main()
{
Outer<int> foo(5);
cout << foo.ptr->val << endl;
testInnerInt(foo.ptr);
//testInnerTemplated(foo.ptr);
testOuter(foo);
}
它运行得很好(打印 5
三次),但如果我取消注释调用 testInnerTemplated
的行,我得到一个编译器错误说 no matching function for call to ‘testInnerTemplated(Outer<int>::Inner*&)’
(在 g++ 4.9.1 中)。我猜是模板查找或匹配的问题,但我如何告诉编译器如何解决它?
最佳答案
template <typename T>
void testInnerTemplated(const typename Outer<T>::Inner*);
编译器无法推断T
通过模板参数推导,因为这是标准中定义的非推导上下文:
The nondeduced contexts are:
The nested-name-specifier of a type that was specified using a qualified-id. A type that is a template-id in which one or more of the template-arguments is an expression that references a template-parameter.
When a type name is specified in a way that includes a nondeduced context, all of the types that comprise that type name are also nondeduced. However, a compound type can include both deduced and nondeduced types. [Example: If a type is specified as
A<T>::B<T2>
, bothT
andT2
are nondeduced. Likewise, if a type is specified asA<I+J>::X<T>
,I
,J
, andT
are nondeduced. If a type is specified asvoid f(typename A<T>::B, A<T>)
, theT
inA<T>::B
is nondeduced but theT
inA<T>
is deduced. ]
关于c++ - 当涉及依赖范围的内部类时,如何使 C++ 找到模板化函数头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942729/