gpt4 book ai didi

c++ - 我应该如何在使用 C++ 模板创建的类之间进行转换?

转载 作者:行者123 更新时间:2023-11-30 00:44:48 25 4
gpt4 key购买 nike

我有一个模板 SoundRecording.h :

template <typename T>
class SoundRecording {
public:
explicit SoundRecording(T init);
private:
T data;
};

template <typename T>
SoundRecording<T>::SoundRecording(T init){
data = init;
}

我可以像这样创建这个模板类的实例:

SoundRecording<int16_t> recording(INT16_MAX);

转换recording 的最佳方法是什么?到 SoundRecording<float>

我知道我可以使用一个简单的方法,例如我可以声明:

SoundRecording<float> convertInt16ToFloat(SoundRecording<int16_t> input)

但我想知道是否有更优雅的方法使用赋值或构造函数运算符来实现此目的。

更新了以下评论:我希望定义一个显式转换。在上面的例子中 recording.data等于INT16_MAX施工后。转换为 float 后它应该等于 1.0F .

最佳答案

你可以有一个模板化的转换运算符,比如

template<class U>
explicit operator SoundRecording<U>() { /*do the conversion here*/ }

举例说明该技术的最小代码片段:

template<class T>
struct X
{
template<class U>
explicit operator X<U>() {return {};}
};

int main()
{
X<int> x;
auto y = static_cast<X<float>>(x); // conversion
}

Live on Coliru

正如@Mooing Duck 在评论中所说,尝试将您的转换运算符标记为 explicit 以避免讨厌的不需要的编译器触发转换。

您可以更进一步,仅当 T 可转换为 U 时启用转换,反之亦然,通过 std::enable_if 的组合和 std::is_convertible ,像这样:

template<class U, 
typename std::enable_if<std::is_convertible<T, U>::value>::type* = nullptr>
explicit operator X<U>() {return {};}

关于c++ - 我应该如何在使用 C++ 模板创建的类之间进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697773/

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