如何检查两种类型是否来自同一模板类 [英] How to check if two types come from the same templated class

查看:59
本文介绍了如何检查两种类型是否来自同一模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查两种类型是否相同,但是不管它们的模板参数如何.像这样:

I would like to check if two types are the same, but regardless of their template parameters. Something like this:

template<class T>
class A {};
class B {};

int main() {
    cout << std::is_same_template<A<int>, A<string>>::value << endl; // true
    cout << std::is_same_template<A<int>, B>::value << endl; // false
}

我知道 std :: is_same 用于检查两种类型是否完全匹配.

I am aware of std::is_same for checking if two types match exacty.

我需要这个的原因:我有一个可以使用任何类型调用的模板化方法,但是我想禁止使用 A 类型(已模板化)调用该方法,可能是通过使用 static_assert .不是 A 的模板,我相信可以使用 std :: is_same 轻松完成,但是现在,我遇到了问题...

A reason why I need this: I have a templated method that can be called with any type, but I would like to prohibit that is is called with type A (which is templated), possibly by using a static_assert. Were A not templated, I believe it could be done easily using std::is_same, but now, I have a problem...

我可以手动排除一些常见的T,使用A,我正在寻找一种针对所有T的方法:

I can manually exclude A for a few common Ts, using, I am looking for a way to do it for all T:

static_assert(!std::is_same<parameter_type, A<int>>::value, "Cannot use this function with type A<T>");
static_assert(!std::is_same<parameter_type, A<double>>::value, "Cannot use this function with type A<T>");
static_assert(!std::is_same<parameter_type, A<bool>>::value, "Cannot use this function with type A<T>");

推荐答案

好吧,

#include <iostream>

template<class T>
struct A {};
struct B {};

template <typename T>
struct should_reject { static constexpr bool value = false; };

template <typename T>
struct should_reject<A<T>> { static constexpr bool value = true; };

template <typename T>
void rejectA(T t)
{
    std::cout << should_reject<T>::value << std::endl;
}

int main() {
    rejectA(B());         // false
    rejectA(1);           // false
    rejectA(1.0);         // false
    rejectA(A<B>());      // true
    rejectA(A<int>());    // true
    rejectA(A<double>()); // true
}

这篇关于如何检查两种类型是否来自同一模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆