gpt4 book ai didi

c++ - 模板偏特化

转载 作者:可可西里 更新时间:2023-11-01 15:47:54 31 4
gpt4 key购买 nike

有人能解释一下为什么编译器无法区分这两个专业吗(gcc 4.5.1 @ideone)

http://ideone.com/9tNux

template <typename... T> struct S;

template<typename A, typename B, typename... C>
struct S<A, B, C...> {
int f() {return 1;}
};

template<typename... A, typename... C>
struct S< S<A...>, C...> {
int f() {return 2;}
};

当我尝试实例化 S<S<a, b>, a, b> o2; 时编译器提示:

prog.cpp:20:21: error: ambiguous class template instantiation for 'struct S<S<a, b>, a, b>'
prog.cpp:6:22: error: candidates are: struct S<A, B, C ...>
prog.cpp:11:33: error: struct S<S<A ...>, C ...>
prog.cpp:20:21: error: aggregate 'S<S<a, b>, a, b> o2' has incomplete type and cannot be defined

而当最后一个专精改为:

template<typename... A, typename B, typename... C>
struct S< S<A...>, B, C...> {
int f() {return 2;}
}

一切正常。

最佳答案

我对这个问题的理解:

typedef S<S<a, b>, c, d> S2;

在这里S<a,b>更好地匹配第二个专业。然而,c, d是第一个特化的剩余参数的更好匹配(单个 arg + 列表 vs 列表)。因此它是 1:1。

如果您在 B 中发表评论在第二个特化中,第二个特化匹配得更好,因为它对第一个参数 (S<...>) 更特化,其余的同样好。

关于c++ - 模板偏特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6988489/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com