gpt4 book ai didi

c++ - 避免采用 int 参数的模板类的 C++ 爆炸式实例化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:30 24 4
gpt4 key购买 nike

假设我有一个 C++ 类:

template<int N>
class Text {
public:
Text() { }
char _buf[N];
};

它只是封装了一个C字符串。

现在,假设我编写了一个方法,它将获取另一个长度为 MText 对象,并将其内容复制到该对象中。

template<int N>
class Text {
public:
Text() { }
char _buf[N];

template<int M> void copy(const Text<M> &t) {
strncpy(_buf, t.cstr(), N - 1);
_buf[N - 1] = '\0';
}
};

这是否会导致重复的目标代码激增,唯一的区别是使用的常量 NM,特别是如果我使用此 copy 方法与具有许多不同的 NM 的对象 ?

由于该方法本身根本不依赖于 M,是否有另一种方法可以避免这种重复目标代码的爆炸式增长?

最佳答案

最明显的方法是将公共(public)位分解为基类,例如:

class TextBase {
public:
char* text;
int n;
TextBase(char* text, int N): text(text), n(N) {}
void copy(const TextBase &t) {
strncpy(this->text, t.text, n - 1);
this->text[n - 1] = '\0';
}
};
template<int N>
class Text: public TextBase {
public:
Text(): TextBase(_buf, N) { }
char _buf[N];
};

它用对象大小换取代码大小的潜在改进。这一定很明显,因为这是我醒来时想到的第一件事。不是根据以类型删除形式获取参数的基数进行旅行,而是避免了额外存储的需要,例如(这种方法是在离醒来有点远的时候想到的):

template<int N>
class Text {
public:
Text() { }
char _buf[N];
operator char const*() const { return this->_buf; }
void copy(char const* source) {
strncpy(this->_buf, source, N - 1);
this->_buf[N - 1] = '\0';
}
};

关于c++ - 避免采用 int 参数的模板类的 C++ 爆炸式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com