【发布时间】:2021-01-25 19:14:38
【问题描述】:
不太确定我的术语是否 100% 正确,所以这里是代码:
template<class... Ts>
struct Empty { };
int main() {
using T = Empty<int, double>;
// How to check if T "contains" double?
return 0;
}
所以这专门用于接受多种模板类型的类型。理想情况下,这也是在编译时。如果不需要该类型的对象,则加分。
我能得到的最接近(help)是这样的:
template <class check, class T, class... U>
constexpr bool contains_type(){
if constexpr (std::is_same_v<T, check>)
return true;
else if constexpr (sizeof...(U) > 0)
return contains_type<check, U...>();
else
return false;
}
template <class check, template<class> class TypeToCheck, class... T>
constexpr bool does_obj_contain_type(TypeToCheck<T...>) {
if constexpr (sizeof...(T) > 0)
return contains_type<check, T...>();
else
return false;
}
constexpr bool does_contain_double = does_obj_contain_type<double>(T{});
它包含我从未见过的 C++ 语法,但它确实有效。如果它不需要T{} 对象,那就太好了。也许看起来更清醒一些。
【问题讨论】:
-
您可以将
T{}替换为std::declval<T>() -
哦,对了,我读到了它,并认为有一天我会使用它。今天有一些,谢谢。
标签: c++ templates c++17 variadic-templates template-meta-programming