我正在使用一些函数模板来按类型存储通用数据。
我定义了我的 template<class T> store()
功能如下。
如果我显式调用类型为 uint64_t
的函数
store<uint64_t>( &p, my_value );
我收到一个编译时错误提示
call of overloaded 'store(char**, uint64_t&)' is ambiguous
candidates are:
void store(char**, T) [with T = long unsigned int]
void store(char**, T2) [with T1 = long unsigned int,
T2 = long unsigned int]
如果我没有类型地编写它,我没有错误(编译器正在推断类型)。
store( &p, my_value );
我注意到编译器假定函数的第二个参数通过引用传递,而我的模板声明必须复制第二个参数。 您知道为什么会发生这种情况以及如何解决这种歧义或在类型声明时更加清晰吗?
最好的问候
AFG
template< class T >
inline void store( char** buffer, T data ){
memcpy( *buffer, &data, sizeof( T ) );
buffer += sizeof(T);
}
template< class T1, class T2 >
inline void store( char** buffer, T2 data ){
memcpy( *buffer, &data, sizeof( T1 ) );
buffer += sizeof(T1);
}
最佳答案
不要使用重载函数。更改第二个过程的名称:
template< class T >
inline void store( char** buffer, T data ){
memcpy( *buffer, &data, sizeof( T ) );
buffer += sizeof(T);
}
template< class T1, class T2 >
inline void store_special( char** buffer, T2 data ){
memcpy( *buffer, &data, sizeof( T1 ) );
buffer += sizeof(T1);
}
使用示例
store_special<uint64_t>( &p, my_value );
关于c++ - 由于模板函数声明中的歧义而出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6408597/