使用专业类中的类模板的内部类型

时间:2015-12-22 15:26:38

标签: c++ templates template-specialization specialization

编辑:当我去度假时,我实际上没有机会测试任何建议的解决方案,当我回来时,负责课程模板的人员我做了一些改变,让我可以解决使用类模板本身定义的类型的需要。

感谢大家的帮助。

简而言之 - 随意纠正我的措辞,模板对我来说仍然有点巫术, - 我需要知道我是否可以使用(protectedstruct或{ {1}}在我的专业类的类模板中定义。例如:

这是课程模板:

#typedef

我需要完全专注于template<typename T> class A : public C<T> { protected: struct a_struct { /* Class template implementation, doesn't depend on T */ }; void foo( a_struct a ); };

T = VAL

但是,如果我这样做,编译器会抱怨template<> class A< VAL > : public C< VAL > { void foo( a_struct a ) { // My implementation of foo, different from the class template's } }; 在我的专门课程中未定义。我尝试了从类模板中专门化和继承,但是......太乱了。

我看到了一些解决方案,但所有这些都涉及修改类模板,这是我无法轻易做到的事情(不同的团队)。

思想?

3 个答案:

答案 0 :(得分:4)

不,您不能在类模板的专门化中使用主模板声明的成员。这是因为从本质上讲,模板类专门化声明了一个全新的类模板,当模板参数与特化时匹配时应用该模板。

如果你想在你的例子中做一些事情,你有两个选择:

  • 您可以专门化模板类成员功能。如果确实只有一个特殊的成员函数(或者至少成员函数的数量有限),这很有用。
  • 您可以将成员(-type)的声明带入公共基类。

由于您在编辑中指出您无法更改类模板本身,因此将成员函数专门化是最佳选择。

仅限成员函数的简化example

template< class T>
class Printer
{
public:
    struct Guard {};
    void DoPrint( const T& val)
    {
        Guard g;
        (void)g;
        std::cout << val << '\n';
    }
};

struct Duck {};

template<>
void Printer<Duck>::DoPrint( const Duck& val)
{
    Guard g;
    (void)g;
    std::cout << "Some duck\n";
}

Guard此处仅用于证明此类型可用于DoPrint()的主要和专业实现。

答案 1 :(得分:1)

它不漂亮,但你可以这样做:

template<typename T>
class C
{

};

template<typename T>
class A : public C<T>
{
protected:
    friend A<int>;
  // ^^^^^^
    struct a_struct { /* Class template implementation, doesn't depend on T */ };
    void foo( a_struct a );
};

template<>
class A< int > : public C< int >
{
    using a_struct = typename A<void>::a_struct;
  // ^^^^^^
    void foo( a_struct a )
    {
        // My implementation of foo, different from the class template's
    }
};

答案 2 :(得分:0)

或如何在专用模板中重新声明struct a_struct,其功能与默认模板相同。

我知道这听起来不太好,因为你需要注入所有专门的模板。但那是我现在能想到的。