jeudi 2 mai 2019

How to reduce duplication when writing traits for reference and non reference types when the traits are the same

I have for example

#include <iostream>

template <typename T>
struct Base {};

template <>
struct Base<std::string> {
  static const int value = true;
};

template <>
struct Base<std::string &> {
  static const int value = true;
};

int main() {
  bool a = Base<std::string>::value;
  bool b = Base<std::string &>::value;

  std::cout << a << b << std::endl;
}

https://godbolt.org/z/0NpYxB

Note I have two specializations that are identical and would like to reduce it to one. There are two solutions I know of which I'd prefer not to do.

(1) Remove the reference at the call site so that only one specialization is required.

(2) Create a base class and inherit the reference and no reference versions from that.

Is there a third option where the specialization is generic over reference and non reference types?

C++11 solutions are required.

Aucun commentaire:

Enregistrer un commentaire