How to explicitly create an instance of a template class with fully specialized members?

Say we have the following files:

foo.h

namespace ns
{
    template <typename T>
    class Foo
    {
    public:
        Foo();

        ~Foo();

        void DoIt();
    };
}

foo.cpp

#include "foo.h"

#include <iostream>

namespace ns
{
    template <typename T>
    Foo<T>::Foo() { std::cout << "Being constructed." << std::endl; }

    template <typename T>
    Foo<T>::~Foo() { std::cout << "Being destroyed." << std::endl; }

    template <>
    void Foo<int>::DoIt()
    {
        std::cout << "Int" << std::endl;
    }

    template <>
    void Foo<double>::DoIt()
    {
        std::cout << "Double" << std::endl;
    }

    template class Foo<int>;
    template class Foo<double>;
}

Is this the right way to instantiate an instance explicitly, assuming that the type will ever be used only with int or double as type parameters? Or do you also need to declare an explicit specialization in the header file?

Performing this as I showed, it works with a visual studio, but a colleague had problems with GCC (although I just checked, and I think that because of something else, I will post this question anyway)

+4
source share
1 answer

[temp.expl.spec] / p6 (my attention):

, - , , , , ; .

, TU, clang gcc . .


, [temp.expl.spec]/p7, :

, , , - , , , , , - , , - - , - , - , -- - .., , , , , .., , . , ; .

+5

All Articles