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/