Initializing static member of nested templated cla

2019-04-16 19:56发布

问题:

Here is my problem:

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    private:
        static int count;
    };

    static int code;
    void print() const
    {
        std::cout << "generic";
    }
};

template<>
template<>
class Outer<bool>::Inner<bool> 
{
    static int count;
};

template<>
template<>
int Outer<bool>::Inner<bool>::count = 4; // ERROR

How do I initialize it properly?

回答1:

Fully-specialized templates are in fact no longer templates, so your definition should simply be:

int Outer<bool>::Inner<bool>::count = 4;

In full, with all definitions in place, your code should look like:

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    private:
        static int count;
    };

    static int code;
    void print() const
    {
        std::cout << "generic";
    }
};

template<typename T>
int Outer<T>::code = 0;

template<typename T>
template<typename U>
int Outer<T>::Inner<U>::count = 0;

template<>
template<>
class Outer<bool>::Inner<bool> 
{
    static int count;
};

int Outer<bool>::Inner<bool>::count = 4;


回答2:

To get one static member per Inner template class instance you can as an alternative use a separate template class.

template<typename T>
class Outer 
{
public:
    template<typename U>
    class Inner 
    {
    };
};

template <typename T>
struct InnerStatic
{
  static int count;
};

template <typename T>
int InnerStatic<T>::count = 4;

int main(int argc, char** argv)
{
  std::cout << InnerStatic<Outer<int>::Inner<int>>::count << std::endl;
  return 0;
}