编译期jni类型转换成字符串

背景:

  例如android jni 方法的签名, 这个需要每个用户都要知道具体类型,转化成签名, 要想写好签名, 必须很熟悉 类型对应的签名, 尤其java类对象要加个L, 本文将介绍怎么在编译期过程把类型转化成字符, 多个类型在尽性拼接.

定义基础数据结构

template
struct charArray
{
	static const char *to_array()
	{
		static const char arr[sizeof ...(ch) + 1] = {ch...};
		return arr;
	}
};

这个里边详细介绍可变参数模版.

定义类型转化成charArray

emplate
struct TypeToChar{};

template<>
struct TypeToChar{
    using TYPE = charArray<'I'>;
    static const char *to_array(){
        return TYPE::to_array();
    }
};

template<>
struct TypeToChar{
    using TYPE = charArray<'J'>;
    static const char *to_array(){
        return TYPE::to_array();
    }
};
template<>
struct TypeToChar{
    using TYPE = charArray<'C'>;
    static const char *to_array(){
        return TYPE::to_array();
    }
};
template<>
struct TypeToChar{
    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
struct concat2{};

template
struct concat2, charArray>
{
     using TYPE=charArray;
     static const char* to_array(){
		return charArray::to_array();
	}
};

template
struct concat{};

template
struct concat{
    using TYPE=typename concat2::TYPE;
    static const char *to_array()
    {
        return TYPE::to_array();
    }
};

把两个类型参数包, 拼接成1个

多类型拼接

template
struct TypesToCharArray {};

template
struct TypesToCharArray {
	using TYPE= typename TypeToChar::TYPE;
	static const char *to_array(){
		return TYPE::to_array();
	}
};

template
struct TypesToCharArray{
	using TYPE = typename concat::TYPE,typename TypeToChar::TYPE>::TYPE;
	static const char *to_array(){
		return TYPE::to_array();
	}
};

template
struct TypesToCharArray{
	using TYPE= typename concat::TYPE, typename TypesToCharArray::TYPE>::TYPE;
	static const char *to_array(){
		return TYPE::to_array();
	}
};

测试demo

int main()
{
	std::cout<::to_array()<::to_array()<, charArray<'e', 'f', 'g'>>::to_array()<::to_array()<::to_array()<::to_array()<::to_array()<

输出结果

abc
efg
abcefg
I
I
ILjava/lang/String;
ILjava/lang/String;JI

你可能感兴趣的:(c++,c++11,c++14,c++,算法,开发语言)