使用模板参数friend从类继承

时间:2014-06-16 21:36:51

标签: c++ c++11

我尝试执行以下操作:我有一个类,每当我声明这个类的新实例时,我想在另一个类中设置一个静态变量。我尝试使用模板进行操作,因此我可以执行class C : public D<AA, BB, CC, DD>之类的操作(使用可变参数)。问题是类AA, BB, CC, DD的静态变量(所有共享相同基数的)都受到保护。因此,我尝试让C成为类的朋友,以便它可以访问变量。

我试过的是:

template <class T>
class Foo
{
    protected:
    static T* t;
    friend T;
};
template <class T>
T* Foo<T>::t = nullptr;

首先我声明了基类Foo,它具有静态变量和friend声明。这意味着要由其他类继承。

然后我做了这个:

template <class Self, class T> //T = Type derived from Foo
struct Bar
{
    Bar()
    {
        T::t = static_cast<Self*>(this);
    }
};

实例化时,哪个类将在T类型中设置静态变量。

这是最后的实施:

struct FooDerived;

struct BarDerived : public Bar<BarDerived, FooDerived>
{

};

struct FooDerived : public Foo<BarDerived>
{

};

我的想法是:

  1. BarDerived会在t
  2. 中设置静态FooDerived
  3. FooDerived继承了Foo<BarDerived>
  4. 的朋友BarDerived
  5. 由于BarDerivedFoo<BarDerived>的朋友,因此可以访问Foo<BarDerived>::t
  6. 但是这不起作用,我得到以下编译错误:

    prog.cpp: In instantiation of ‘void Bar<Self, T>::test() [with Self = BarDerived; T = FooDerived]’:
    prog.cpp:37:9:   required from here
    prog.cpp:11:4: error: ‘BarDerived* Foo<BarDerived>::t’ is protected
     T* Foo<T>::t = nullptr;
        ^
    prog.cpp:18:8: error: within this context
       T::t = static_cast<Self*>(this);
            ^
    

    https://ideone.com/jcRcH0

    我是否因为我期望模板/友谊的行为而错过了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:https://ideone.com/RW3xfV

template <class T>
class Foo
{
protected:
    static T* t;
    template <class Self, class U> //T = Type derived from Foo
    friend struct Bar;
};

因为Bar需要访问Foo<T>::t

相关问题