模板类实例之间的类型转换

时间:2019-06-15 11:15:21

标签: c++ templates casting type-conversion

我目前正在尝试使用c ++样式类型转换。为此,我创建了一个模板类pClass,它接受​​类型T的某些元素并将其打印出来。

现在,我想(例如)将类型为pClass<char>的实例转换为pClass<int>。但是,非我的类型转换尝试似乎按预期方式工作。

我已经发现dynamic_cast用于在运行时以及处理虚拟函数/多态类时进行转换,在此情况并非如此。 static_cast用于在编译时进行转换。因此,我认为static_cast应该是正确的选择?

一些关于stackoverflow的主题也有类似的问题,但是仅当处理多个类并在它们之间进行继承时才有类似的问题。不幸的是,我无法真正将它们与我的问题联系起来(例如C++ Casting between template invocations)。

#include <iostream>

template <typename T>
class pClass {
    public:
    T value;
    pClass(T value) {
        this->value = value;
        std::cout << value << std::endl;
    }
    virtual ~pClass() {}
};

int main() {
    pClass<int> pInt(5);
    pClass<char> pChar('a');
    pClass<float> pFloat(4.2f);

    // pClass<int> pInt2 = static_cast<pClass<int>&>(pChar); //  gives invalid type conversation
    // pClass<int>& pInt3 = dynamic_cast<pClass<int>&>(pChar); // warning: dynamic_cast of ‘pClass<char> pChar’ to ‘class pClass<int>&’ can never succeed
    // pClass<int> pInt4 = reinterpret_cast<pClass<int>&>(pChar); // works, but does not print anything
    // std::cout << pInt2.value << std::endl; // prints 3277 or even 327777 exept of 97, which is the expected ASCII representation
}

对于每次强制转换尝试,我都会在命令后面写入错误消息/输出结果。我很感谢有任何提示可以帮助我在这里找到正确的类型。

非常感谢您!

1 个答案:

答案 0 :(得分:5)

尽管类型来自同一模板,但它们是完全无关的。您不能只在它们之间进行强制转换,编译器如何才能知道强制转换的含义?由于模板的特殊性,pClass<char>甚至可能不包含可以强制转换为char的{​​{1}}。

解决方案是使用 cast 转换运算符写出铸造的含义

int

上述方法允许通过强制转换存储的值在任意两个template <typename T> class pClass { public: T value; pClass(T value) { this->value = value; std::cout << value << std::endl; } virtual ~pClass() {} template<typename U> operator pClass<U>(){ return pClass<U>(static_cast<U>(this->value)); } }; pClass<T>之间进行强制转换。这将使以下代码编译:

pClass<U>

第二行是复制构造函数pClass<int> pInt{1}; pClass<float> pfloat{pInt}; ,它使用隐式强制转换将pClass<float>::pClass<float>(const pClass<float>&);转换为pInt类型。

我建议使转换运算符明确:

pClass<float>

这将禁止上面的隐式转换,但仍然允许显式转换:

template<typename U> explicit operator pClass<U>()