0

It's hard to explain clearly, so sorry for unclear title. I need template class, that takes list of strings (char* ?) as template parameter. This class must have static method static string get(int i);, that will return nth string from passed as template static list of string. How can it be coded?

Goal is to make child classes with assigned list of strings. Something like this:

class Letters : public Base<"A", "B", "C"> {};
...
std::cout << Letters::get(1);
Rinat
  • 1,941
  • 2
  • 17
  • 26

2 Answers2

4

As Dragos Pop mentioned in the comments, it is impossible to use a string literal as a template argument.

Possible workarounds:

  • If you only need letters, consider using char:

    Base<'A', 'B', 'C'>
    
  • Consider passing callable object types instead of string literals. The callable objects will return the string literals you require.

    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> { /* ... */ }; 
    
Community
  • 1
  • 1
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
1

If you're using C++11, you can get the same behavior easily using std::tuple, here is the code

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;
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36