call base class constructor without naming its class

送分小仙女□ 提交于 2019-12-10 16:44:16

问题


class MyDerived: public Incredble<Difficult< And<Complicated, Long>>, And<Even, Longer>, BaseClass, Name>
{
public:
  MyDerived();
}


MyDerived::MyDerived
: ???(params)
{}

Is there any way to call a base constructor without writing its full name and without typedeffing it?

The reason is clearly to avoid code duplication and introducing multiple positions to change if a detail in the base class template params changes.

Level 2 of this:

template <uint32 C>
class MyDerived: public Incredble<Difficult< And<Complicated, Long>>, And<Even, Longer>, BaseClass, Name>
{
public:
  MyDerived();
}

template <uint32 C>
MyDerived::MyDerived<C> 
: ???(C)
{
}

回答1:


You could use injected-class-name. Incredible<...>::Incredible refers to itself, and since MyDerived isn't a class template, unqualified lookup will look in the scope of its base classes:

MyDerived::MyDerived
: Incredble(params)
{}

If Incredible is a dependent name, then you need to qualify it. You can actually simply use the derived type name to qualify the base class's injected-class-name (h/t Johannes Schaub-litb):

MyDerived::MyDerived
: MyDerived::Incredible(params)
{}

This will work in all cases.




回答2:


If you don't wont to use using or typedef to avoid "polluting the enclosing namespace", you can use using inside the class/struct.

An example

#include <map>

template <typename ...>
class foo
 {};

struct A : public foo<int, std::tuple<long, char, std::map<std::string, int>>>
 {
   using base_t = foo<int, std::tuple<long, char, std::map<std::string, int>>>;

   A () : base_t{}
    { };
 };

int main()
 { } 


来源:https://stackoverflow.com/questions/39413091/call-base-class-constructor-without-naming-its-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!