c++ - 在 C++ 中定义类型转换运算符模板的正确方法是什么

标签 c++

this此处的代码是我尝试定义一个模板以进行类型转换或赋值运算符。问题是,这不是在对对象进行类型转换时在第 27 行调用类型转换函数模板。

#include <iostream>
#include <string>

using namespace std;
struct FFJSON{
    template <typename T>
    FFJSON& operator=(T const& t){
        cout << "Assigning the object" << endl;
        ts=(void*)&t;
        return *this;
    };
    FFJSON& operator=(const char* s){return *this;};
    FFJSON& operator=(const string& s){return *this;};
    FFJSON& operator=(const int& i){return *this;};
    FFJSON& operator=(const unsigned int& i){return *this;};
    template <typename T>
    operator T(){
        cout << "Returning the object." << endl;
        return *ts;
    }
    void* ts;
};
int main(int argh, char** argv) {
    FFJSON f;
    timespec tt = {3,2};
    f = tt;
    timespec& t=(timespec&)f;
    cout << "sec:"<<t.tv_sec<<endl;
    cout << "usec:"<<t.tv_nsec<<endl;
    return 0;
}

实际输出:

Assigning the object
sec:126885484802960
nsec:4197094

预期输出:

Assigning the object
Returning the object
sec:3
nsec:2

类似的情况是在另一个程序中出现类型转换运算符未定义的编译时错误。

最佳答案

template <typename T> operator T()很好,但是这样T只能推断为非引用 类型,因此该运算符不会用于转换为类型 timespec& .相反,您的类型转换是 reinterpret_cast ,它从不执行用户定义的转换。

为了编写可以产生左值的转换运算符,您需要编写 template <typename T> operator T&() .

顺便说一句,您不能取消引用 void 指针。如果您的运算符模板曾经被实例化,您将因此得到一个编译错误。

关于c++ - 在 C++ 中定义类型转换运算符模板的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216650/

相关文章:

c# - C# 中的 _BitScanForward?

c++ - 在哪里制作类的逻辑?

c++ - 在配置脚本名称中使用指定版本的 find_package

c++ - 将 2 位十进制转换为十六进制

C++ 隐式复制构造函数和赋值运算符

c++ - 替换字符串中的多对字符

c++ - strcmpi 整数,无转换错误

c++ - 在 Visual Studio 调试器中,{null=???} 是什么意思?

c++ - 如何在 Windows 7 下在内存有限的计算机上读取大文件?文件大小为 25GB 但 RAM 容量仅为 16GB

C++,两个有共同需求的类