[英]what is the right way to define typecast operator template in C++
此处的这段代码是我尝试定义用于类型转换或赋值运算符的模板。 问题是,这不是在类型转换对象时在第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
类似的情况是,在另一个程序中,typecast运算符没有定义编译时错误。
template <typename T> operator T()
很好,但是只能将T
推导出为非引用类型,因此不会将该运算符转换为timespec&
类型。 相反,您的类型转换是reinterpret_cast
,它从不执行用户定义的转换。
为了编写可以产生左值的转换运算符,您需要编写template <typename T> operator T&()
。
顺便说一句,您不能取消引用空指针。 如果曾经实例化您的操作员模板,则将因此而导致编译错误。
timespec& t=(timespec&)f;
无法使用类型转换运算符,因为您要转换为timespec&
而不是timespec
。
你必须实现
operator T&(){
cout << "Returning the object." << endl;
return *reinterpret_cast<T*>(ts);
}
使这项工作。
请不要在C ++模块中使用C样式的强制转换。 使用static_cast<>
, dynamic_cast<>
, reinterpret_cast<>
和-如果确实需要const_cast<>
。
我不确定您要实现的目标,但是赋值运算符的以下实现将复制源值,并且应适用于临时对象,而类型转换运算符将检查转换是否有效。
class FFJSON
{
public:
template <typename T>
inline FFJSON& operator=(T const& t){
cout << "Assigning the object" << endl;
assert(std::is_trivially_copyable<T>::value );
data.resize(sizeof(t));
*reinterpret_cast<T*>(data.data()) = t;
return *this;
};
template <typename T>
inline operator T(){
cout << "Returning the object." << endl;
assert(sizeof(T) <= data.size());
return *reinterpret_cast<T*>(data.data());
}
private:
std::vector<char> data;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.