不太确定我的术语是否 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{}
对象,那就太好了。也许看起来更理智一些。
最佳答案
不确定你到底想要什么......但我想是这样的
template <class check, template<class...> class TypeToCheck, class... T>
constexpr bool does_obj_contain_type(TypeToCheck<T...>) {
return (std::is_same_v<check, T> || ...);
}
// ...
using T = Empty<int, double>;
auto x = does_obj_contain_type<double>(T{});
但是如果无法实例化 T
类型的对象,就会出现问题。在这种情况下,我想您可以使用类/结构特化。
有点像
template <typename>
struct does_obj_contain_type;
template <template <typename...> class TTC, typename ... Ts>
struct does_obj_contain_type<TTC<Ts...>>
{
template <typename check>
static constexpr bool func ()
{ return (std::is_same_v<check, Ts> || ...); }
};
// ...
using T = Empty<int, double>;
constexpr auto x = does_obj_contain_type<T>::func<double>();
或者作为模板变量值
可能更好( super 建议:谢谢!)
template <template <typename...> class TTC, typename ... Ts>
struct does_obj_contain_type<TTC<Ts...>>
{
template <typename Check>
static constexpr auto value = (std::is_same_v<Check, Ts> || ...);
};
// ...
using T = Empty<int, double>;
constexpr auto x = does_obj_contain_type<T>::value<double>;
关于c++ - 是否可以检查类型是否已使用特定模板参数实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65891004/