将 const char* 作为模板参数传递 [英] Passing const char* as template argument

查看:44
本文介绍了将 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* 作为模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆