模板化赋值运算符:有效的 C++?

发布于 2024-07-15 17:57:46 字数 175 浏览 3 评论 0原文

只是一个快速而简单的问题,但在任何文档中都找不到它。

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

它用 g++ 编译,但我不确定这是否有效。 是吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

总以为 2024-07-22 17:57:46

是的,这段代码是正确的。 有关详细信息,请参阅此 C++ 模板教程

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

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

仙女山的月亮 2024-07-22 17:57:46

这是有效的 C++,但它与模板化赋值运算符无关?! 该代码段定义了 SomeClass 的静态成员,并将其初始值设置为 NULL。 只要您只执行一次就可以了,否则您就会踩到可怕的一个定义规则

模板赋值运算符类似于:

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;
}

模板赋值运算符对于在实现类变体时提供转换最有用。 如果您要使用这些生物,则应该考虑很多注意事项。 Google 搜索将会发现有问题的案例。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文