假设我在不同的命名空间中有几个同名的类。
namespace A { class Foo { ... }; }
namespace B { class Foo { ... }; }
namespace C { class Foo { ... }; }
如果类名为 Foo
,我想在编译时进行检测尽管命名空间。例如一些 SFINAE 类,
template <typename T> struct is_Foo {
static const bool value = /* some magic here */;
};
那我要is_Foo<A::Foo>::value
是真的,is_Foo<B::Foo>::value
是真的,is_Foo<A::Bar>::value
是假的。
然后,我想使用 is_Foo
在 static_assert
或 std::enable_if
.可能吗?
最佳答案
template <typename T>
struct is_Foo : public std::false_type {
};
template <>
struct is_Foo<A::Foo> : public std::true_type {
};
template <>
struct is_Foo<B::Foo> : public std::true_type {
};
template <>
struct is_Foo<C::Foo> : public std::true_type {
};
这通过制作 is_Foo<T>
来实现继承自 std::true_type
对于 T
的特化作为A::Foo
等并继承自 std::false_type
对于任何其他 T
.如您所见,没有使用 SFINAE,仅使用了继承和模板特化。
这可以用于 static_assert
和 enable_if
.
如果你不想专攻is_Foo
对于每个类(class),您必须按照评论中的建议让类(class)“合作”。一种方法是创建一个类并使所有这些类都继承该类。该类可以有一个你可以检查的特殊成员,或者你可以检查是否 T
is_base_of
那个类。
关于c++ - 在不同的命名空间中测试特定的类名(SFINAE?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22449368/