簡體   English   中英

如何在構造函數中限制char數組長度

[英]How to limit char array length in constructor

使用擴展嵌入式Cpp。 如何在發布版本中的編譯錯誤中生成此結果:

Param okParam("Yeah!"); // this line should be ok
Param nOkParam("REEEEEEEEEEE"); // too big array, not ok. compiler error.

哪里:

int const c_max = 10;

template<int N>
struct Param
{
  char value[c_max];

  Param(char const (&p_value)[N])
  {
     memcpy(value, p_value, sizeof(p_value));
  }
};

我不認為你可以模板化構造函數,所以整個結構需要模板化,對吧?


我希望這提供一個干凈的編譯器錯誤,以便使用它的人會立即注意到它。

我們的擴展嵌入式C ++版本不提供任何stl容器,我不確定它是否可行。

我正在尋找一些方法來使模板結果出現良好的編譯錯誤。 可悲的是,我也不能使用boost,因為平台不支持它。

您基本上有兩個解決方案: SFINAE (C ++ 98)或static_assert (C ++ 11):

SFINAE

您只能為小於給定大小的char數組提供Param的構造函數。 在C ++ 98中,這看起來有點難看,但它有效:

#include <cstddef>

template<bool b>
struct enable_if {};

template<>
struct enable_if<true>
{
    typedef int type;
};


template<std::size_t MAXSIZE>
struct Param
{
    template<std::size_t SIZE>
    explicit Param(
        char const (&input) [SIZE],
        std::size_t = sizeof(typename enable_if<SIZE < MAXSIZE>::type) // SFINAE at work
    ) { (void) input; }
};

int main()
{
    // "hello": char const[6], 6 < 7, OK
    Param<7> p1("hello");

    // "hello world": char const[12], 12 >= 7, KO
    Param<7> p2("hello world"); // ugly error here
}

現場演示

斷言(僅限C ++ 11)

Param的構造函數中,您可以檢查提供的char數組是否太大並在編譯時彈出可讀錯誤:

#include <cstddef>
#include <type_traits>

template<std::size_t MAXSIZE>
struct Param
{
    template<std::size_t SIZE>
    explicit Param(char const (&input) [SIZE])
    { static_assert(sizeof(input) < MAXSIZE, "input is too big."); }
};

int main()
{
    // "hello": char const[6], 6 < 7, OK
    Param<7> p1("hello");

    // "hello world": char const[12], 12 >= 7, KO
    Param<7> p2("hello world"); // "error: static assertion failed: input is too big."
}

現場演示

也許最簡單的方法是添加一個static_assert ,使用一個舊的C技術編譯時檢查 ,如果你的執行不具有static_assert尚未:

#include <cstring>

#if __cplusplus < 201103L
#define static_assert(expr, message)                                    \
    int static_assert_(int (&static_assert_failed)[(expr)?1:-1])
#endif

template<int N>
struct Param
{
    static const int c_max = 10;
    static_assert(N < c_max, "Param string too long");
    char value[c_max];

    Param(char const (&p_value)[N])
    {
        std::memcpy(value, p_value, sizeof p_value);
    }
};

int main()
{
    Param okParam("Yeah!"); // this line should be ok
    Param nOkParam("REEEEEEEEEEE"); // too big array, not ok. compiler error.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM