创建别名时静态断言模板参数检查
Static assert template parameter check while creating an alias
假设我们有一个结构,我需要检查模板参数的类型(wchar_t只是一个例子):
template <typename T>
struct Foo {
static_assert(std::is_same<T, wchar_t>::value, "Failure");
}
当然,以下代码不会编译:
Foo<int> foo;
但是我如何阻止编译:
using foo = Foo<int>;
如果您真的想在using FooINT = Foo<int>;
行上产生错误,您可以使用默认的模板参数:
template <
typename T,
typename = std::enable_if_t<std::is_same<T, wchar_t>::value>
>
struct Foo { };
当您尝试实际创建foo
时,它不会编译?一旦foo
是一个变量,一旦它是一个类型,就可以更改它的含义。
#include <iostream>
using namespace std;
template <typename T>
struct Foo {
static_assert(std::is_same<T, wchar_t>::value, "Failure");
};
using FooINT = Foo<int>;
int main() {
FooINT foo; // breaks
return 0;
}
所以你基本上定义了一个无用的类型别名。不幸的是,创建特定的别名并不能立即实例化该类型。
详细说明一下。using
只是引入了一个别名,它不会"生成"类型,因此以下情况是可能的:
#include <iostream>
using namespace std;
template <typename T>
struct Foo {
static_assert(std::is_same<T, wchar_t>::value, "Failure");
};
using FooINT = Foo<int>; // should it break now or not?
template <>
struct Foo<int> {
int A_OK;
};
int main() {
FooINT foo; // works now
return 0;
}
所以你不能让using FooINT = Foo<int>;
自己不编译。您需要一些机制来实际实例化模板。
相关文章:
- 如何检查给定的参数是否为 cv::noArray()?
- 用于检查值是否为其任何参数的帮助程序函数
- 模板化检查是否存在带有参数列表的类成员函数?
- SFINAE 检查模板参数运算符
- 检查两个模板参数是否相同
- 使用参数包自动执行dynamic_cast检查
- 检查类是否具有模板专用化(使用布尔值或 int 等模板参数)
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 如何检查参数包是否具有执行顺序中的确切类型
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 如何检查模板参数是否为给定值?
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- 如何在 C++ 中检查类构造函数中的参数大小
- 检查模板类型 T 是否为 C++17 中的可变参数包的一部分
- 递归回文检查,不使用向量、大小或其他参数
- 空参数检查C++
- 创建别名时静态断言模板参数检查
- 参数检查
- 通过main传递参数-检查输入是否有效