C++模板元编程
我刚刚开始使用模板元编程,所以我只是尝试做一些基本的事情。我得到了适用于 BST 的 Size 和 Lookup “方法”,所以我决定尝试创建一个 String 类。我在 cpp 文件中有这段代码:
#include <iostream>
#include <string>
using namespace std;
struct Null;
// String
template <char C, typename S>
struct String {
static const char chr = C;
typedef S tail;
};
// ToString
template <typename S>
struct ToString;
template <char C, typename S>
struct ToString<String<C, S> > {
static const string str;
};
template <char C, typename S>
const string ToString<String<C, S> >::str = C + ToString<S>::str; // (*)
template <char C>
struct ToString<String<C, Null> > {
static const string str;
};
template <char C>
const string ToString<String<C, Null> >::str = C + ""; // to make it a string
int main() {
typedef String<'H', String<'e', String<'l', String<'l',
String<'o', Null> > > > > myString;
cout << ToString<myString>::str << endl;
return 0;
}
当我运行它时,这段代码输出“Hell”。我在基本情况下做错了什么?它似乎与“”有关,因为我曾经将 C + ToString
::str 作为 "" + C + ToString
::str< /code> 位于 (*)
行,然后输出是随机垃圾。
I'm just starting out with template metaprogramming so I'm just trying to make some basic things to begin with. I got Size and Lookup "methods" working for a BST, so I decided to try making a String class. I have this code in a cpp file:
#include <iostream>
#include <string>
using namespace std;
struct Null;
// String
template <char C, typename S>
struct String {
static const char chr = C;
typedef S tail;
};
// ToString
template <typename S>
struct ToString;
template <char C, typename S>
struct ToString<String<C, S> > {
static const string str;
};
template <char C, typename S>
const string ToString<String<C, S> >::str = C + ToString<S>::str; // (*)
template <char C>
struct ToString<String<C, Null> > {
static const string str;
};
template <char C>
const string ToString<String<C, Null> >::str = C + ""; // to make it a string
int main() {
typedef String<'H', String<'e', String<'l', String<'l',
String<'o', Null> > > > > myString;
cout << ToString<myString>::str << endl;
return 0;
}
This code outputs "Hell" when I run it. What am I doing wrong in the base case? It seems to have something to do with the "", because I used to have C + ToString<S>::str
as "" + C + ToString<S>::str
on line (*)
and the output then was random junk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
"" + C + ToString
::str首先执行指针加法,然后才进行串联,要一直执行字符串串联std::string("") + C + ToString
::str"" + C + ToString<S>::str
first performs pointer addition, and only later concatenation, to do string concatenation all the way dostd::string("") + C + ToString<S>::str