問題描述
為什么你不能在這里傳遞文字字符串?我通過一個非常小的解決方法使它工作.
Why can't you pass literal strings in here? I made it work with a very slight workaround.
template<const char* ptr> struct lols {
lols() : i(ptr) {}
std::string i;
};
class file {
public:
static const char arg[];
};
decltype(file::arg) file::arg = __FILE__;
// Getting the right type declaration for this was irritating, so I C++0xed it.
int main() {
// lols<__FILE__> hi;
// Error: A template argument may not reference a non-external entity
lols<file::arg> hi; // Perfectly legal
std::cout << hi.i;
std::cin.ignore();
std::cin.get();
}
推薦答案
因為這不是一個有用的實用程序.由于它們不是模板參數的允許形式,因此目前不起作用.
Because this would not be a useful utility. Since they are not of the allowed form of a template argument, it currently does not work.
讓我們假設它們有效.因為對于所使用的相同值,它們不需要具有相同的地址,所以即使您的代碼中具有相同的字符串文字值,您也會獲得不同的實例化.
Let's assume they work. Because they are not required to have the same address for the same value used, you will get different instantiations even though you have the same string literal value in your code.
lols<"A"> n;
// might fail because a different object address is passed as argument!
lols<"A"> n1 = n;
您可以為您的文本編輯器編寫一個插件,用逗號分隔的字符文字列表替換字符串并返回.使用可變參數模板,您可以以某種方式解決"這個問題.
You could write a plugin for your text editor that replaces a string by a comma separated list of character literals and back. With variadic templates, you could "solve" that problem this way, in some way.
這篇關于將 const char* 作為模板參數傳遞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!