c – 如何检查两个类型是否来自同一个模板类

参见英文答案 > Check if two types are of the same template                                    3个
我想检查两种类型是否相同,但不管它们的模板参数如何.像这样的东西:

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用于检查两个类型是否匹配exacty.

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

编辑:
我可以手动排除A为几个常见的Ts,使用,我正在寻找一种方法为所有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
}
上一篇:javascript – 检查对象是否是一个有前途的功能


下一篇:python – TypeError:需要一个float