提问者:小点点

模板基类初始化


如何初始化模板基类的成员?

template<class base>
struct child: base
{
    child(float a, float b):
        child::a(a), // doesnt work
        base::b(b) // doesnt work
    {}
};


struct base
{
    int a;
    int b;
};

using example = child<base>;

显然,base{a,b}可以工作。 但那不是我想做的。


共1个答案

匿名用户

这段代码足以修复您所显示的内容,但仍然不清楚您实际上想要做什么。 代码仍然不是很好,但是它在您给出的指令下工作,即base不能被触及。 我去掉了模板的东西,因为它是可能的(也许不实际)得到一些没有模板的编译的东西。 当知道什么需要通用时,它可以很容易地被修复为与模板一起工作。

struct Base {
  int a;
  int b;
};

struct Child : public Base {
  Child(float a, float b) : Base{static_cast<int>(a), static_cast<int>(b)} {}  // Data loss
};

int main() { Child child(3.14f, 9.81f); }

这里有一个子模板类,我不能假定它是正确的。 但是同样的指令是base不能被触及。

struct Base {
  int a;
  int b;
};

// Will fail spectacularly for any type that can't be converted to int
// Could be remedied with some SFINAE, but I only know enough about that
// to know it's an option. It's also quite likely not what's desired anyway
template <typename T>
struct Child : public Base {
  Child(T a, T b) : Base{static_cast<int>(a), static_cast<int>(b)} {}
};

int main() { Child<float> child(3.14f, 9.81f); }

如果base中的类型是泛型,那么您完全不需要继承。

template <typename T>
struct Base {
  T a;
  T b;
};

int main() { Base<float> base{3.14f, 9.81f}; }