Passing const char* as template argument(将 const char* 作为模板参数传递)
问题描述
为什么你不能在这里传递文字字符串?我通过一个非常小的解决方法使它工作.
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* 作为模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 const char* 作为模板参数传递


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07