我在一些我想使用的庫中找到了這個函式,但我不知道將一個std::string變數傳遞給它
----------
template<int KeyLen>
std::vector<unsigned char> key_from_string(const char (*key_str)[KeyLen]) {
std::vector<unsigned char> key(KeyLen - 1);
memcpy(&key[0], *key_str, KeyLen - 1);
return key;
}
test_encryption.cpp
const std::vector<unsigned char> key2 = plusaes::key_from_string(usr_key.c_str());
這就是我試圖呼叫該函式的方式
錯誤
test_encryption.cpp: In function 'std::__cxx11::string encrypte_string(std::__cxx11::string, std::__cxx11::string)':
test_encryption.cpp:39:82: error: no matching function for call to 'key_from_string(const char*)'
const std::vector<unsigned char> key2 = plusaes::key_from_string(usr_key.c_str()); // 16-char = 128-bit
^
In file included from test_encryption.cpp:1:
pulse.hpp:685:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[17])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[17]) {
^~~~~~~~~~~~~~~
pulse.hpp:685:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[17]'
pulse.hpp:690:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[25])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[25]) {
^~~~~~~~~~~~~~~
pulse.hpp:690:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[25]'
pulse.hpp:695:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[33])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[33]) {
^~~~~~~~~~~~~~~
pulse.hpp:695:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[33]'
uj5u.com熱心網友回復:
庫中的函式只接受指向字串文字的指標。例子:
std::vector<unsigned char> key = plusaes::key_from_string(&"Foo");
這里KeyLen將被推匯出,4因為字串文字由'F', 'o', 'o', '\0'
您提供usr_key.c_str()給回傳 a 的函式,這const char*與這樣的函式不匹配。所有模板引數在編譯時都必須是已知的,并且KeyLen是這樣的引數。它必須是編譯時常量。
另一種方法是std::vector<unsigned char>手動創建:
std::vector<unsigned char> key2(usr_key.begin(), usr_key.end());
或者,如果需要,創建自己的輔助函式:
std::vector<unsigned char> my_key_from_string(const std::string& s) {
return {s.begin(), s.end()};
}
并像這樣使用它:
auto key2 = my_key_from_string(usr_key);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403645.html
標籤:
上一篇:縮短R中的長向量
下一篇:如何找出字串中哪個元音最多
