我正在嘗試將文字字串作為 C 14 專案中的模板引數傳遞。谷歌告訴我,我可以這樣做:
struct Test {
static const char teststr[];
template<const char* str>
void p() {std::cout << str;}
};
const char Test::teststr[] = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
它確實奏效了。
但是,如果我使用const char*, 而不是const char []. 它行不通。
struct Test {
static const char* teststr;
template<const char* str>
void p() {std::cout << str;}
};
const char* Test::teststr = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
現在它不起作用。編譯器告訴我'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable。
嗯,我不知道是什么意思。
uj5u.com熱心網友回復:
編譯器的錯誤資訊很清楚:
錯誤:“Test::teststr”不是有效的模板引數,因為“Test::teststr”是一個變數,而不是變數的地址
所以你需要:
#include <iostream>
struct Test {
static const char* teststr;
template<const char **str>
void p() {std::cout << *str;}
};
const char* Test::teststr = "Hello world!";
int main() {
Test t;
t.p <&Test::teststr>();
}
然后它就起作用了——關鍵是變數的[內容]不是編譯時常量,而變數的地址(如果它是靜態變數或全域變數)是。
uj5u.com熱心網友回復:
這只是根據c 的規則:
模板非型別引數。
對于指向物件的指標,模板引數必須指定具有靜態存盤持續時間和鏈接(內部或外部)的完整物件的地址
https://en.cppreference.com/w/cpp/language/template_parameters
全域字符陣列具有鏈接,而字串文字沒有。
在 C 20 中,這已被更改,您可以使用字串文字作為模板引數。
uj5u.com熱心網友回復:
問題是,在您的示例的情況 2 中,靜態資料成員是teststr一個指標型別,它具有標準不允許的字串文字的地址,從下面參考的陳述句可以看出,
來自非型別模板引數的檔案:
非型別模板引數的模板引數應是模板引數型別的轉換常量運算式(5.20)。對于參考或指標型別的非型別模板引數,常量運算式的值不應參考(或對于指標型別,不應是地址):
(1.1) 子物件 (1.8),
(1.2) 臨時物件 (12.2),
(1.3)字串文字(2.13.5),
因此,如果您的示例中的 2teststr不能使用,因為它是具有字串字面地址的指標型別 "Hello world!"。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481813.html
上一篇:c :算術運算子多載
