背景:
例如android jni 方法的签名, 这个需要每个用户都要知道具体类型,转化成签名, 要想写好签名, 必须很熟悉 类型对应的签名, 尤其java类对象要加个L, 本文将介绍怎么在编译期过程把类型转化成字符, 多个类型在尽性拼接.
定义基础数据结构
template<char ... ch>
struct charArray
{
static const char *to_array()
{
static const char arr[sizeof ...(ch) + 1] = {ch...};
return arr;
}
};
这个里边详细介绍可变参数模版.
定义类型转化成charArray
emplate<typename T>
struct TypeToChar{};
template<>
struct TypeToChar<int>{
using TYPE = charArray<'I'>;
static const char *to_array(){
return TYPE::to_array();
}
};
template<>
struct TypeToChar<long>{
using TYPE = charArray<'J'>;
static const char *to_array(){
return TYPE::to_array();
}
};
template<>
struct TypeToChar<char>{
using TYPE = charArray<'C'>;
static const char *to_array(){
return TYPE::to_array();
}
};
template<>
struct TypeToChar<std::string>{
using TYPE = charArray<'L','j', 'a','v','a','/','l', 'a', 'n', 'g', '/','S','t','r','i','n','g',';'>;
static const char *to_array(){
return TYPE::to_array();
}
};
这里定义了类型, 以及对应的类型转化的签名, 接下来看下多个类型进行拼接带啊吗
拼接
template<typename ...T>
struct concat2{};
template<char ...ch1, char ...ch2>
struct concat2<charArray<ch1...>, charArray<ch2...>>
{
using TYPE=charArray<ch1..., ch2...>;
static const char* to_array(){
return charArray<ch1..., ch2...>::to_array();
}
};
template<typename ...T>
struct concat{};
template<typename T, typename U>
struct concat<T,U>{
using TYPE=typename concat2<T,U>::TYPE;
static const char *to_array()
{
return TYPE::to_array();
}
};
把两个类型参数包, 拼接成1个
多类型拼接
template<typename ...Args>
struct TypesToCharArray {};
template<typename T>
struct TypesToCharArray<T> {
using TYPE= typename TypeToChar<T>::TYPE;
static const char *to_array(){
return TYPE::to_array();
}
};
template<typename T, typename U>
struct TypesToCharArray<T, U>{
using TYPE = typename concat<typename TypeToChar<T>::TYPE,typename TypeToChar<U>::TYPE>::TYPE;
static const char *to_array(){
return TYPE::to_array();
}
};
template<typename T, typename U, typename ...Args>
struct TypesToCharArray<T, U, Args...>{
using TYPE= typename concat<typename TypesToCharArray<T,U>::TYPE, typename TypesToCharArray<Args...>::TYPE>::TYPE;
static const char *to_array(){
return TYPE::to_array();
}
};
测试demo
int main()
{
std::cout<<charArray<'a','b','c'>::to_array()<<std::endl;
std::cout<<charArray<'e','f','g'>::to_array()<<std::endl;
std::cout<<concat2<charArray<'a','b','c'>, charArray<'e', 'f', 'g'>>::to_array()<<std::endl;
std::cout<<TypeToChar<int>::to_array()<<std::endl;
std::cout<<TypesToCharArray<int>::to_array()<<std::endl;
std::cout<<TypesToCharArray<int, std::string>::to_array()<<std::endl;
std::cout<<TypesToCharArray<int, std::string,long,int>::to_array()<<std::endl;
return 0;
}
输出结果
abc
efg
abcefg
I
I
ILjava/lang/String;
ILjava/lang/String;JI
文章评论