mercredi 2 décembre 2020

Implement template function for generic parameter [duplicate]

Suppose I have a template function, and I wish to implement it for a specific parameter. This is simple:

template<typename T>
T foo();

// specific implementation for int
template<>
int foo() { /*...*/ }

// generic implementation
template<typename T>
T foo() { /*...*/ }

What if I need to have a specific implementation for a family of types? By family I mean a type with template parameter(s) of its own, e.g. std::vector. Let's say I happen to know which vector types I will need. Then I can do this:

template<typename T>
T foo();

// specific implementation for std::vector<int>
template<>
std::vector<int> foo() { /*...*/ }

// specific implementation for std::vector<long>
template<>
std::vector<long> foo() { /*...*/ }

struct SomeOtherType { /*...*/ };
// specific implementation for std::vector<SomeOtherType>
template<>
std::vector<SomeOtherType> foo() { /*...*/ }

// generic implementation
template<typename T>
T foo() { /*...*/ }

If the implementations of foo() for those vector types are the same, this is a little bit redundant. What if I don't know all the vector types beforehand, but need the implementation for any std::vector<V> to be different than the generic implementation? Either way, it would be nice to do something like this:

template<typename T>
T foo();

// specific implementation for any kind of std::vector
template<???>
std::vector<V> foo() { /*...*/ }

// generic implementation
template<typename T>
T foo() { /*...*/ }

Is there a way to do something like this? Can the design be re-worked to make this possible/easier?

Aucun commentaire:

Enregistrer un commentaire