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* 作为模板参数传递


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01