2017-01-16 46 views
0

很难清楚解释,所以对于不清楚的标题感到抱歉。我需要模板类,它将字符串列表(char *?)作为模板参数。这个类必须有静态方法static string get(int i);,它将返回作为模板静态列表字符串传递的第n个字符串。它如何编码?以字符串列表作为模板参数的模板静态类,如何在C++上编写11

目标是让子类具有指定的字符串列表。事情是这样的:

class Letters : public Base<"A", "B", "C"> {}; 
... 
std::cout << Letters::get(1); 
+1

http://stackoverflow.com/questions/1826464/c-style-strings-as-template-arguments –

回答

4

由于德拉戈什流行在评论中提到的,it is impossible to use a string literal as a template argument

可能的解决方法:

  • 如果你只需要字母,可以考虑使用char

    Base<'A', 'B', 'C'> 
    
  • 考虑通过调用对象类型代替字符串文字。可调用对象将返回您需要的字符串文字。

    struct String0 
    { 
        constexpr auto operator()() const noexcept 
        { 
         return "some string 0"; 
        } 
    }; 
    
    struct String1 
    { 
        constexpr auto operator()() const noexcept 
        { 
         return "some string 1"; 
        } 
    }; 
    
    class Words : public Base<String0, String1> { /* ... */ }; 
    
+0

谢谢!认为这是“真正的方式” – Rinat

1

如果您使用C++11,你可以很容易地使用std::tuple相同的行为,这里是代码

typedef std::tuple<string, string, string> mytpl; 

mytpl tpl = make_tuple("A", "B", "C"); 

cout << get<0>(tpl).c_str() << endl; 
cout << get<1>(tpl).c_str() << endl; 
cout << get<2>(tpl).c_str() << endl; 
相关问题