首页 > 解决方案 > 为什么概念类模板特化会导致错误

问题描述

我尝试使用 gcc 10 构建以下内容-std=gnu++20 -fconcepts

template <std::signed_integral T>
class MyClass{ T a; };

template <std::unsigned_integral T>
class MyClass{ T a; };

为什么这段代码会导致以下错误?

> declaration of template parameter ‘class T’ with different constraints
> 55 | template <std::unsigned_integral T>
>       |           ^~~

不应该没问题吗?

标签: template-specializationc++20c++-conceptsclass-templategcc10

解决方案


不应该没问题吗?

不,约束不会使类“可重载”。您仍然需要一个主模板,然后您需要专门化该模板:

template <std::integral T>
class MyClass;

template <std::signed_integral T>
class MyClass<T>{ T a; };

template <std::unsigned_integral T>
class MyClass<T>{ T a; };

推荐阅读