gpt4 book ai didi

c++ - 基于其他模板定义从模板类到原始类型的隐式转换

转载 作者:行者123 更新时间:2023-11-30 05:08:27 25 4
gpt4 key购买 nike

我有一个由两个模板定义的类。

template<typename A, typename B> my_class {
private:
A value;

public:
operator A () {
return this->value;
}
};

我想在模板中定义类和第一种类型之间的隐式转换,但只针对模板中特定的第二种类型。由于 A 是 C++ 原始类型,因此我无法在那一侧定义转换。我试过 std::enable_if 这样的

operator typename std::enable_if<std::is_same<B, specific_B_type>::value, NumT>::type () {
return this->value;
}

但是我得到了编译错误

Error   C2833   'operator type' is not a recognized operator or type    dimensional_analysis

有什么方法可以做到这一点而不必定义专门用于 B = specific_B_type 的整个类?

最佳答案

您可以使用 static_assert 来检查是否允许转换:

operator A() 
{
static_assert(std::is_same<B, specific_B_type>::value, "No conversion possible");
return this->value;
}

但是,这意味着如果 B 不是 specific_B_type,则无法显式转换为 A。如果你需要,你可以看看this的答案。关于根据模板参数添加和删除成员的问题。

关于c++ - 基于其他模板定义从模板类到原始类型的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840294/

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