C++组合参数模板元编程
C++ combining arguments template metaprogramming
我是C++中模板和元编程的新手。我现在要做的是:我有一个带有模板的结构,它需要类型为char的非类型可变包,定义如下:
template <char ... chs>
struct MyStruct
{};
我有第二个结构模板,它需要两种类型,如下所示:
template <typename ch1, typename ch2>
struct Together
{
};
我正在努力实现的是:
cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result << 'n';
必须打印:abcd
提前感谢
使用模板,可以通过部分专业化实现模式匹配。像这样声明主模板声明:
template <typename First, typename Second>
struct Together;
然后以某种方式定义具有"外观"的类型的部分专业化:
template <char... ch1s, char... ch2s>
struct Together<MyStruct<ch1s...>, MyStruct<ch2s...>>
{
std::string result;
Together() : result({ch1s..., ch2s...}){}
};
这是一个可能的解决方案,使用std::string result:与问题非常匹配
template <char ... chs>
struct MyStruct
{
static string stringify()
{
return stringify(chs...);
}
template <typename ... cst>
static string stringify()
{
return string();
}
template <typename T, typename ... cst>
static string stringify(T c, cst... cs)
{
return string() + c + stringify<cst...>(cs...);
}
};
template <typename ch1, typename ch2>
struct Together
{
static string result() {return ch1::stringify() + ch2::stringify();}
};
int main() {
cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result() << 'n';
return 0;
}
它当然会或多或少地使用模板参数,比如:
Together<MyStruct<'a','b','c','d'>, MyStruct<'e','f','g'>>::result()
以下是@Ryan Haining的答案的一个小改进:
template <char... Chars>
struct MyStruct
{
static constexpr char value[] {Chars..., ' '};
};
template <char... Chars>
constexpr char MyStruct<Chars...>::value[];
template <typename, typename>
struct Together;
template <char... Chars1, char... Chars2>
struct Together<MyStruct<Chars1...>, MyStruct<Chars2...>>
{
using type = MyStruct<Chars1..., Chars2...>;
};
现场演示
相关文章:
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 可组合的lambda/std::函数与std::可选
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 混合组合和继承的C++问题
- 我需要将多个函数组合为一个函数
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 通过组合不同的类型来创建唯一的id
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 模板元编程:如何将参数包组合成新的参数包
- Qt Q串行端口未编程设备未关闭
- 检查向量是否具有所有可能的字符组合
- 如何在加密++中将两个源组合成新的源
- 如何使用任何编程语言组合序列中的多个图像
- 组合两个用不同高级语言编程的 Web 组装组件
- 在C++编程语言中,如何用n个向量长度的所有可能的字符串组合来填充向量
- 面向对象编程和对象组合,如何放置组合属性?
- C++组合参数模板元编程
- 套接字编程:组合来自fork()-ed进程的数据