【问题标题】:Is it possible to make a string as a template parameter?是否可以将字符串作为模板参数?
【发布时间】:2013-07-11 15:39:35
【问题描述】:

是否可以将字符串作为模板参数以及如何?喜欢

A<"Okay"> is a type.

任何字符串(std::string 或 c-string)都可以。

【问题讨论】:

  • 是的,但它并不是很有帮助,因为它的行为不像你所期望的那样(它使用指针相等,而不是字符串相等)。
  • 嗯...您可能会制作一个可变参数模板,将一堆字符作为模板输入。至少它会给你真正的字符串等价。 std::string 将不起作用,因为模板参数必须是 integral 类型。
  • @Aggieboy 或指向具有外部链接的对象的指针或引用。 (字符串文字不起作用,因为它们没有外部链接。)
  • @JamesKanze Ahh 详情;引用只是一个指针,一个指针只是一个 int,而一个 int 是一个整数。 XD

标签: c++ templates


【解决方案1】:

是的,但您需要将其放入具有外部链接的变量中 (或者 C++11 是否删除了对外部链接的要求)。 基本上,给定:

template <char const* str>
class A { /* ... */ };

这个:

extern char const okay[] = "Okay";

A<okay> ...

有效。注意认为它是 not 字符串的内容 它定义了唯一性,但对象本身:

extern char const okay1[] = "Okay";
extern char const okay2[] = "Okay";

鉴于此,A&lt;okay1&gt;A&lt;okay2&gt; 具有不同的类型。

【讨论】:

    【解决方案2】:

    这是使字符串内容确定唯一性的一种方法

    #include <windows.h> //for Sleep()
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    template<char... str>
    struct TemplateString{
        static const int n = sizeof...(str);
        string get() const {
            char cstr[n+1] = {str...}; //doesn't automatically null terminate, hence n+1 instead of just n
            cstr[n] = '\0'; //and our little null terminate
            return string(cstr); 
        }
    };
    
    int main(){
        TemplateString<'O','k','a','y'> okay;
        TemplateString<'N','o','t',' ','o','k','a','y'> notokay;
        cout << okay.get() << " vs " << notokay.get() << endl;
        cout << "Same class: " << (typeid(okay)==typeid(notokay)) << endl;
        Sleep(3000); //Windows & Visual Studio, sry
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2015-01-09
      相关资源
      最近更新 更多