anc*_*anc 1 c++ inheritance templates c++11
假设有以下场景:
class A {};
class B : public A {};
class C : public A {};
class D : public A {};
template<typename T/*std::enable_if and std::is_base_of here*/> class X {};
Run Code Online (Sandbox Code Playgroud)
当我宣布 X
然后我想约束typename T必须是 A 的子类,否则我会得到一个编译错误。
int main()
{
X<B> x1 = {}; //should work;
X<C> x2 = {}; //should work;
X<D> x2 = {}; //should work;
X<std::string> = {}; //should generate a compiling error;
X<int> = {}; //should generate a compiling error;
};
Run Code Online (Sandbox Code Playgroud)
正确的使用语法enable_if是
template<typename T, std::enable_if_t<std::is_base_of_v<A, T>, bool> = true>
class X {};
Run Code Online (Sandbox Code Playgroud)
现在 if是thenA的基础,并且成为,我们赋予它 的值。如果不是 的基础,则条件为假,结果为空,模板将作为可行的候选者被丢弃,并且将生成编译器错误。Tstd::is_base_of_v<A, T>truestd::enable_if_tbooltrueATstd::enable_if_t