Any*_*orn 7 c++ inheritance templates
我试图解决问题,但找到了不同的解决方案.但出于好奇,想知道以下是否可行:
template< class > struct S;
template< > struct S< Foo > : struct< Foo > {};
Run Code Online (Sandbox Code Playgroud)
我希望能够从专门的struct继承非专用结构.上面的例子不起作用,因为继承的结构是专用的,导致无限递归.
一种可能的解决方案是添加第二个模板参数,比如bool special,这样默认值为false,而专用模板的参数为true.但是,由于实例化需要指定其他参数,因此会使事情变得有点混乱.
有没有其他方法来实现上述?
最初的问题是实现矩阵矩阵,其中矩阵本身可能有额外的运算符,这取决于组成矩阵是否有那些运算符.我希望这是有道理的.同时,不同的专用矩阵需要具有相同的基类,同时保留相同的名称,尽管具有不同的模板参数.我以为可能有办法使用enable_if和type traits
您可以将所有通用内容保存在单独的类型中,并使用您的专业化扩展它:
template <typename> struct S_generic { /* generic stuff here */ };
template <typename T> struct S : public S_generic<T> { /* nothing here */ };
template <> struct S<Foo> : public S_generic<Foo> { /* extra stuff here */ };
Run Code Online (Sandbox Code Playgroud)
编辑:或者,如果您不喜欢额外的名称,在实例化模板时使用额外标志而没有混乱的方法是使用默认值:
template <typename T, bool fully_defined=true> struct S;
template <typename T> struct S<T,false> { /* generic stuff here */ };
template <typename T> struct S<T,true> : public S<T,false> {};
template <> struct S<Foo,true> : public S<Foo,false> { /* extra stuff here */ };
Run Code Online (Sandbox Code Playgroud)
一种可能的解决方案是添加第二个模板参数,例如 boolspecialized,这样默认值为 false,而专用模板的该参数为 true。但是,这使事情变得有点混乱,因为实例化需要指定其他参数。
你可以这样做template<class Foo, bool flag = false>,所以第二个参数是可选的。