3

次のようなヌル終了を保証する char buf ラッパーを作成しようとしています。

template<size_t N> class BufStr
{
public:
    explicit BufStr(const char(&buf)[N])
    {
        memcpy(m_buf, buf, N);
        m_buf[N-1] = '\0';
    }

    inline const char* c_str() const { return m_buf; }

protected:
    char m_buf[N];
};

しかし、署名テンプレートを使用して、char buf をコンストラクターに直接渡し、sizeof を使用して配列のサイズを決定できるようにしたいので、コンパイル時に N を計算します。

4

2 に答える 2

2

編集済みゼロで終了していない文字配列を「ラップ」したいという事実を説明するには:

「工場」機能を持つことができます:

template <size_t N> 
   BufStr<N+1> make_bufstr(const char(&buf)[N])
{
    return BufStr<N+1>(buf);
}

デモ ( のstd::copy代わりに を使用していることに注意してくださいmemcpy):

#include <cstdint>
#include <algorithm>

template<std::size_t N> class BufStr
{
public:
    explicit BufStr(const char(&buf)[N-1])
    {
        static_assert(N>0, "illegal size");
        std::copy(buf, buf+N-1, m_buf);
        m_buf[N-1] = '\0';
    }

    inline const char* c_str() const { return m_buf; }

protected:
    char m_buf[N];
};

template <size_t N> 
   BufStr<N+1> make_bufstr(const char(&buf)[N])
{
    return BufStr<N+1>(buf);
}

int main()
{
    const char raw[] = { 'H', 'e', 'l', 'l', 'o' }; // no NUL termination!
    auto s = make_bufstr(raw); // adds terminating NUL
}
于 2013-09-21T21:54:14.377 に答える