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

Ana*_*Ana 5 c++ templates

假设我有一个C++类:

template<int N>
class Text {
    public:
        Text() { }
        char _buf[N];
};
Run Code Online (Sandbox Code Playgroud)

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

现在,假设我编写了一个方法,它将获取另一个Text具有长度的对象,M并将其内容复制到此对象中.

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';
        }            
};
Run Code Online (Sandbox Code Playgroud)

这会导致重复的目标代码爆炸,唯一的区别是常量NM使用,特别是如果我使用这个copy方法与有很多不同的对象NM

由于方法本身根本不依赖M,是否有另一种方法来解决这个问题,以避免重复的目标代码爆炸?

Die*_*ühl 3

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

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];
};
Run Code Online (Sandbox Code Playgroud)

它以对象大小来换取代码大小的潜在改进。这一定是显而易见的,因为这是我醒来时想到的第一件事。不是按照基数进行旅行,而是以类型擦除形式获取参数,从而避免了额外存储的需要,例如(当距离醒来还远一点时,我想到了这种方法):

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';
    }
};
Run Code Online (Sandbox Code Playgroud)