下面这段代码有什么问题?
#include <iostream>
template<typename K>
struct A {
struct X { K p; };
struct Y { K q; };
};
template<typename K>
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
std::cout << "A" << std::endl;
}
int main() {
A<float>::X x;
A<float>::Y y;
foo(x, y);
}
clang 给出以下错误消息:
17:2: error: no matching function for call to 'foo'
foo(x, y);
^~~
10:6: note: candidate template ignored: couldn't infer template argument 'K'
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
^
1 error generated.
最佳答案
参数 K
在 const typename A<K>::X
不可推断。基本上,::
剩下的所有内容不可演绎(如果 ::
分隔嵌套名称)。
通过运行这个思想实验来了解为什么要求推理没有意义是微不足道的:
struct A { typedef int type; }
struct B { typedef int type; }
template <typename T> void foo(typename T::type);
foo(5); // is T == A or T == B ??
从类型到嵌套类型没有一对一的映射:给定任何类型(例如 int
),可能有许多环境类型是嵌套类型,或者不需要任何类型。
关于c++ - 候选模板被忽略,因为无法推断模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12566228/