Cha*_*ani 0 c++ templates memcpy
为什么以下不编译:
struct Carrier
{
void* data;
int StrategyRequestType;
Carrier(int StrategyRequestType )
{
StrategyRequestType = StrategyRequestType;
}
template <typename T>
bool loadStrategyRequestType(T)
{
data = malloc(sizeof(T));
memcpy ( data, &T, sizeof(T) ); // Syntax error here - "expected primary expression before ',' token"
return true;
}
};
Run Code Online (Sandbox Code Playgroud)
什么方法可以使它工作?
template <typename T>
bool loadStrategyRequestType(T)
{
data = malloc(sizeof(T));
memcpy ( data, &T, sizeof(T) ); // Syntax error here - "expected primary expression before ',' token"
return true;
}
Run Code Online (Sandbox Code Playgroud)
你不能指向一个类型的指针.如果要将对象t复制到数据,请执行以下操作:
template <typename T>
bool loadStrategyRequestType(T t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
Run Code Online (Sandbox Code Playgroud)
以上可能工作正常,但在创建对象时仍可能进行复制.因为,对象没有改变,为了确保没有复制对象,这会更好:
template <typename T>
bool loadStrategyRequestType(const T& t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
Run Code Online (Sandbox Code Playgroud)
正如我在评论中提到的,在实现函数模板时,如果c ++ 11可用,最好使用通用引用.为什么?因为它们涵盖了所有可能的情况
template <typename T>
bool loadStrategyRequestType(T&& t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
Run Code Online (Sandbox Code Playgroud)