将 const char* 作为模板参数传递

Passing const char* as template argument(将 const char* 作为模板参数传递)
本文介绍了将 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* 作为模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)