gpt4 book ai didi

c++ - 如何外部化转换运算符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:39 24 4
gpt4 key购买 nike

我如何做到这一点,以便将以下代码外化到类之外:

template<typename TemplateItem>
class TestA
{
operator const int (){return 10;}
};

所以它看起来像:

template<typename TemplateItem>
class TestA
{
operator const int ();
};

template<>
TestA<int>::operator const int()
{
//etc etc
}

所以我可以针对不同的模板类型专门化函数?

最佳答案

这样写:

template <typename T> class TestA
{
operator const int();
};

template <typename T> TestA<T>::operator const int()
{
return 10;
}

顺便说一句,“inline”的标准反义词通常是“out of line”。此外,我可能会将函数设为 const,就像通常使用转换运算符所做的那样(以允许从常量对象进行转换)。

您可以特化整个类,也可以只特化成员函数。仅对于成员函数,这样写:

template <> TestA<int>::operator const int() { /* ... */ }

对于整个类特化,语法是这样的:

template <> class TestA<int>
{
operator const int();
};
TestA<int>::operator const int() { /*...*/ }

关于c++ - 如何外部化转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7680274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com