c++ - C 样式字符串作为模板参数?

标签 c++ templates string

C-Style 字符串可以用作模板参数吗?

我试过了:

template <char *str>
struct X
{
    const char *GetString() const
    {
         return str;
    }
};

int main()
{
    X<"String"> x;
    cout<<x.GetString();
}

虽然我对类定义没有任何提示,但实例化会产生 'X' : invalid expression as a template argument for 'str' (VC)。

最佳答案

A string literal cannot be used as a template argument .

更新:如今,在这个问题被问及回答几年后,可以使用字符串文字作为模板参数。使用 C++11,我们可以使用字符包作为模板参数 (template<char ...c>) 和 is possible将文字字符串传递给这样的模板。

但是,这会起作用:

template <char const *str>
struct X
{
    const char *GetString() const
    {
         return str;
    }
};

char global_string[] = "String";

int main()
{
    X<global_string> x;
    cout<<x.GetString();
}

关于c++ - C 样式字符串作为模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826464/

相关文章:

c++ - 何时使用 std::forward 转发参数?

c# - C#中的字符串字符差异

c++ - 如何使用 Qt 库从文本文件中获取字符串

c++ - 在 C++ 中,为重载函数强制转换为子类?

c++ - 模板等价还是模板功能等价?

templates - 用于 Web 开发的 QuickStart 基本布局/模板?

python - python中的质量字符串替换?

JavaScript:如何从一个元素的所有后代获取文本,而不考虑脚本?

c++ - 使用多线程调试 DLL (/MDd) C 运行时库构建静态 Opencv 库

c++ - 表示纪元之前的日期