简体   繁体   中英

fixed vector as template parameter on c++ class

I want to create a class like this:

template<std::vector<char> ID>
class test
{
      std::vector<char> m_id=ID;
 public:
      std::vector<char> getID()
      { 
           return ID;
      }
}

and then use it such as this:

typedef test1234 test<{'1','2','3','4','5'}>
test1234 t1;
std::cout <<t1.getID()<<std:;endl;

How can I do this?

The idea is that I can define several classes with the same functionality, but different ID. I don't want to pass the ID as construction parameters (I know how to do that way!).

I am using VS 2013.

If you change your problem from "how to initialize a vector with template parameter" (to which there is no solution with VS2013) to "how to have different constructors parametrised with template arguments" then I have a solution. You should define array of strings and pass a subscript for that array, that would sove it:

std::string initializers[]={{'1','2','3','4','5'},"Hello moto"};

template<int ID>
class test
{
      std::vector<char> m_id{initializers[ID].begin(),initializers[ID].end()};
 public:
      std::vector<char> getID()
      { 
           return  std::vector<char> {initializers[ID].begin(),initializers[ID].end()};
      }
};

Which will make following valid:

int main()
{
    typedef  test<1> test1234;
    test1234 t1;
    std::cout <<t1.getID()[0] <<std::endl; // you obviously do not have stream output operator for vector
}

Add const s to your taste and probably encapsulate initializers if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM