2012-09-24 48 views
19

以下代码段有什么问题?候选模板被忽略,因为无法推断模板参数

#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); 
} 

铛提供了以下错误消息:

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. 

回答

37

的参数Kconst 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),可能有许多环境类型,它是嵌套类型,或者不需要。

6
template<typename K> 
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) { 
    std::cout << "A" << std::endl; 
} 

K不能推导出,因为它是在non-deduced背景。

n3337 14.8.2.5/4

在某些情况下,然而, 值不参与型扣,而是使用了 要么别处推导或明确指定的模板参数的值。 如果仅在未推导的 上下文中使用模板参数,且未明确指定模板参数,则模板参数推导失败

n3337 14.8.2.5/5

非推导上下文是:

- 这是使用合格-id指定的类型的嵌套名称说明符。