如何解决如何检查类型是否从模板函数中的某个可变参数模板类实例化?
假设我有:
template <typename...>
class Foo { };
然后我定义另一个函数:
template <typename... T>
void Bar(const T&... arguments) { }
如何检查传递给 T
的所有 Bar
是否都从 Foo
实例化?喜欢:
Foo<int> a;
Foo<int,int> b;
Bar(a,b); // OK
int c;
Bar(a,b,c); // ill-formed
我想要一种方法来检测格式错误的参数,例如 Bar(a,c);
有没有办法做到这一点?
解决方法
您可以创建一个特征来测试 Foo
的实例化,然后将其折叠到您的所有参数中。
template <typename>
struct is_foo : std::false_type {};
template <typename... Ts>
struct is_foo<Foo<Ts...>> : std::true_type {};
template <typename T>
constexpr bool is_foo_v = is_foo<T>::value;
template <typename... T>
void Bar(const T&... arguments) {
static_assert((is_foo_v<T> && ...),"arguments must all be Foos");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。