views:

469

answers:

2

Just a quick and simple question, but couldn't find it in any documentation.

template <class T>
T* Some_Class<T>::Some_Static_Variable = NULL;

It compiles with g++, but I am not sure if this is valid usage. Is it?

+6  A: 

Yes this code is correct. See this C++ Templates tutorial for more information

http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm#T14

JaredPar
@Daniel: Also, [cplusplus.com](http://www.cplusplus.com/doc/tutorial/templates/) explains templates very well.
Lazer
A: 

That is valid C++ but it has nothing to do with a templated assignment operator?! The snippet defines a static member of SomeClass<T> and sets its initial value to NULL. This is fine as long as you only do it once otherwise you step on the dreaded One Definition Rule.

A templated assignment operator is something like:

class AClass {
public:
    template <typename T>
    AClass& operator=(T val) {
        std::ostringstream oss;
        oss << val;
        m_value = oss.str();
        return *this;
    }
    std::string const& str() const { return m_value; }
private:
    std::string m_value;
};

std::ostream& operator<<(std::ostream& os, AClass const& obj) {
    os << obj.str();
    return os;
}

int main() {
    AClass anObject;
    anObject = 42;
    std::cout << anObject << std::endl;
    anObject = "hello world";
    std::cout << anObject << std::endl;
    return 0;
}

The template assignment operator is most useful for providing conversions when implementing variant-like classes. There are a bunch of caveats that you should take into consideration if you are going to use these critters though. A Google search will turn up the problematic cases.

D.Shawley