简体   繁体   中英

run-time calculations with non-type variadic templates

Is it possible to make run time calculations with non-type variadic templates?

Imagine the following situation:

template<unsigned int... indexes>
struct s
{
   unsigned int getPosition(const unsigned int target) const;
};

s<2,5,0,7> obj;
std::cout << obj.getPosition(5) << std::endl; //< this should output 1
std::cout << obj.getPosition(2) << std::endl; //< this should output 0

The getPosition method should return the position of the given integer in the template parameter pack. If the given integer is not present in the parameter pack, an error (preferably at compile time) should be generated.

PS I know how to do this if the signature is changed to

template<unsigned int... indexes>
struct s
{
   template<unsigned int target>
   unsigned int getPosition() const;
};

Unfortunately, this is not an option for me as the method should be virtual.

You could dump the indexes into a std::array and use std::find .

struct s
{
   unsigned int getPosition(const unsigned int target) const {
       static std::array<int, sizeof...(indexes)> indexArray { indexes... };
       auto pos = std::find(std::begin(indexArray), std::end(indexArray), target);

       if (pos == std::end(indexArray)) {
           //handle error, probably an exception   
       }

       return std::distance(std::begin(indexArray), pos);
   }
};

You can't generate a compile-time error if target doesn't exist, as you only know target at run-time.

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