定义从模板 class 到基于其他模板的基本类型的隐式转换

define implicit conversion from template class to primitive type based on other template

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

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

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

我想在 class 和模板中的第一种类型之间定义一个隐式转换,但只针对模板中特定的第二种类型。由于 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 的整个 class?

您可以使用 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 关于根据模板参数添加和删除成员的问题的答案。