[英]Auto non-type template parameter: ambiguous partial specializations in Clang
Clang (7, 8, trunk) rejects the following code Clang(7,8,trunk)拒绝以下代码
enum class E {};
inline static constexpr auto e = E{};
// inline static constexpr auto e = nullptr;
template<auto, int> class S;
template<int a, int b> class S<a, b> {};
template<int b> class S<e, b> {};
int main() {
S<0, 0> s;
}
with an error: 有错误:
error: ambiguous partial specializations of 'S<0, 0>' note: partial specialization matches [with a = 0, b = 0] template<int a, int b> class S<a, b> {}; ^ note: partial specialization matches [with b = 0] template<int b> class S<e, b> {}; ^
Why is it ambiguous? 为什么它含糊不清? How can e
match 0
? 如何e
比赛0
? If I replace E{}
with nullptr
, Clang stops complaining. 如果我用nullptr
替换E{}
,Clang就会停止抱怨。 This looks like a Clang's bug. 这看起来像是Clang的错误。 GCC compiles it just fine. GCC编译得很好。
If it is a bug, what is a workaround? 如果是一个bug,那么解决方法是什么? In my case, the auto
parameter can be either E
(and only one value E{}
) or int
. 在我的例子中, auto
参数可以是E
(只有一个值E{}
)或int
。 Then: 然后:
template<auto, int, typename> class S_impl; template<int a, int b> class S_impl<a, b, int> {}; template<int b> class S_impl<e, b, E> {}; template<auto a, int b> using S = S_impl<a, b, decltype(a)>;
Is there a more succinct way? 有更简洁的方式吗?
Clang is doing the deduction wrong. Clang做的演绎错了。 It is similar to this bug , linked to this question (not exactly identical as you are using auto in template parameters which will prevent you to compile using stdc++14). 它类似于这个bug ,链接到这个问题 (如你在模板参数,这将阻止你使用STDC ++ 14编译使用自动并不完全相同)。
An interesting case is that it is not the case if it's a complete specialization; 一个有趣的案例是,如果它是一个完整的专业化则不是这样的; only on partial specialization : 仅限部分专业化:
#include <iostream>
enum class E {};
inline static constexpr auto e = E{};
template <auto a, int b>
class FOO;
template <int a, int b > class FOO<a, b> {};
template <int b> class FOO<e, b> {};
template <auto a, int b>
class BAR;
template <int a, int b > class BAR<a, b> {};
template <> class BAR<e, 0> {};
template <auto a>
class BAZ;
template <int a> class BAZ<a> {};
template <> class BAZ<e> {};
int main() {
// FOO <0, 0> foo; // <= Not Ok
BAR<0, 0> bar; // <= Ok
BAZ<0> baz; // <= Ok
}
Any solution that force the deduction of the type template parameter will work therefore your suggested solution is perfectly valid. 任何强制扣除类型模板参数的解决方案都可以使用,因此您建议的解决方案完全有效。 IMHO, I would avoid using auto in template parameter when not necessary to improve readability : 恕我直言,如果没有必要提高可读性,我会避免在模板参数中使用auto:
template <typename T, T value, int> class S_impl; // <= this auto is not necessary
template <int a, int b> class S_impl<int, a, b> {};
template <int b> class S_impl<E, e, b> {};
// Either define S to use S<0,0> or directly use S_impl<int, 0, 0>
template <auto a, int b> using S = S_impl<decltype(a), a, b> // <= this auto is necessary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.