[英]Templated assignment operator: valid C++?
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.它使用 g++ 编译,但我不确定这是否有效。 Is it?是吗?
Yes this code is correct.是的,这段代码是正确的。 See this C++ Templates tutorial for more information有关更多信息,请参阅此 C++ 模板教程
http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm#T14 http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm#T14
That is valid C++ but it has nothing to do with a templated assignment operator?!这是有效的 C++ 但它与模板化赋值运算符无关?! The snippet defines a static member of SomeClass<T>
and sets its initial value to NULL
.该片段定义了SomeClass<T>
的 static 成员,并将其初始值设置为NULL
。 This is fine as long as you only do it once otherwise you step on the dreaded One Definition Rule
.这很好,只要你只做一次,否则你会踩到可怕的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.谷歌搜索会发现有问题的案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.