类模板的编译错误,但其专业化除外

Compile error for class template except its specializations

本文关键字:专业化 错误 编译      更新时间:2023-10-16

我想禁止所有类型的类模板,除了class专门用于使用静态断言的类型。请检查以下代码:

template <typename Type>
class foo {
static_assert(false, "Wrong Type");
};
template <>
class foo<int> {
};
int main()
{
foo<int> fi;    // should compile
foo<double> fd; // should not compile
return 0;
}

但它不起作用。经过一些研究,我发现了一个问题来回答我的问题:通过static_assert 强制模板类型

我已经根据问题更新了代码:

template <typename Type>
class foo {
static_assert(sizeof(Type) == -1, "Wrong Type!");
};
template <>
class foo<int> {
};

int main()
{
foo<int> fi;    // should compile
foo<double> fd; // should not compile
return 0;
}

我的问题是为什么第二个版本可以,为什么第二版本不行?

这么简单:

template <typename Type>
class foo; // just don't provide an implementation...
template <>
class foo<int> { };