【发布时间】:2019-02-08 09:29:33
【问题描述】:
在类模板Foo 中,我想检查模板参数是否提供名为Bar 的类型。
struct TypeA {using Bar = int;};
struct TypeB {};
template<class T>Foo{};
void main(){
Foo<TypeA> a; // I want this to compile
Foo<TypeB> b; // I want this to not compile, but print a nice message.
}
因为我想将它与其他属性结合起来,所以我想要一个hasBar 元函数。所以我可以组合布尔值,然后使用std::enable_if。
我试图理解和使用 SFINAE 但失败了:
template<class T, class Enable = void>struct hasBar : std::false_type {};
template<class T>
struct hasBar<T,decltype(std::declval<T::Bar>(),void())> : std::true_type {};
hasBar<TypeA>::value 始终为假。
定义hasBar的正确方法是什么?
或者有没有比using 更好的方法来拥有一个酒吧?
【问题讨论】:
-
当引用嵌套依赖类型时,您需要直接指定名称是 type 而不是 e.g.静态字段...所以在
T::Bar之前使用typename关键字