2

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

A<"Okay"> is a type.

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

4

2 回答 2

2

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

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

这个:

extern char const okay[] = "Okay";

A<okay> ...

作品。注意认为定义唯一性的不是字符串的内容,而是对象本身:

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

鉴于此,A<okay1>A<okay2>有不同的类型。

于 2013-07-11T16:05:48.607 回答
1

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

#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
}
于 2013-07-11T16:41:29.980 回答