c++ - 候选模板被忽略,因为无法推断模板参数

标签 c++ templates

下面这段代码有什么问题?

#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.

最佳答案

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

关于c++ - 候选模板被忽略,因为无法推断模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12566228/

相关文章:

python - 将计算结果插入 LaTeX 文档

C++设计问题: Passing functions via templates?

c++ - 如何在 C++ 类中初始化 char *? (sizeof() 总是给出 8)

c++ - 在 C++ 中将子 vector 作为函数参数传递

c++ - 关闭控制台时如何正确处理 SIGBREAK?

c++ - 模板和方法特化

c++ - 将不同枚举类类型作为输入的函数,怎么样?

c++ - Qmake给我错误

c++ - Delphi/C++Builder 10.2.3 RESTRequest POST

c++ - 为什么这个函数不能用明显不同的签名之一重载?