c++visual-studio-2010templatesc++11inherited-constructors

c++0x inherited constructor in templates


Here is class foo:

template <typename T>
struct foo
{
    foo()
    {
        t = nullptr;
    }

    foo(T* p, bool flag)
    {
        t = p;
    }
private:
    T* t;
};

Here is class bar:

template <typename T>
struct bar: public foo<T>
{
    using foo<T>::foo<T>;
};

Is it correct syntax for inheriting constructors? If I use "using foo::foo;" then compiler of Visual C++ 2010 dies. So basically how to inherit constructors from template classes in VC++ 2010?


Solution

  • template <typename T>
    struct bar: public foo<T>
    {
        using foo<T>::foo<T>;
    };
    

    To let this parse correctly, you would need to insert template before the foo<T>;, to tell the compiler that foo is to be regarded as a template name (it cannot look into foo<T> to tell itself, since T is unknown). But using ::template is not allowed in a using declaration. The name also does not refer to all constructors of bar: Instead, it would refer to a specific constructor function template specialization (T is the template argument) of such a constructor as follows

    template<typename T>
    foo();
    

    In addition, it's not valid for a using declaration to use a template-id (like foo<T>) as its name (which in effect forbids it to refer to function template specialization, with the addition of forbidding to name conversion function template specializations stated too), so even if you correct the parsing problem using ::template (if it would be possible), you would still error out at this point.

    When inherited constructors were introduced, special rules were added that allow to reference a constructor using a syntactic rule: If you have a qualified-id (which basically a qualified name using ...::...), and the last qualified before the final part names a specific class, then you can denote the constructor(s) of that class in two additional ways:

    These two additional rules are only active in a using declaration. And they were naturally not present in C++03. The other rule that was also present in C++03 is: If the final part names the injected class name, then this qualified name also refers to the constructor:

    Therefor, with the special rules in place you can write

    using foo<T>::foo;
    using bar::foo::foo; // valid too
    

    The second is valid too: foo is the injected class name which was injected into the base class foo<T> and inherited to bar. We refer to that name by bar::foo, and then add the last part foo, which refers to the injected class name again, to denote the constructor(s) of `foo.

    Now you understand why the initial name you tried would refer to a constructor function template specialization (if it were to be allowed to): Because the foo<T>::foo part would name all constructors, and the <T> that would follow would then filter out the template and pass the type argument.