Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template non-type parameter with different types

Let's assume an input template parameter T may or may not have internal variable bar. I am trying to write a struct that returns the value of bar when we have it, and returns some constant when we don't. Here is my attempt:

struct A {
  static constexpr unsgined int bar = 20;
  hasBar = true;
};

struct B {
  hasBar = false;
};

template <typename T, typename std::enable_if<T::hasBar, int>::type>
struct getBar {
  static constexpr unsigned int bar = T::bar;
};

template <typename T, typename std::enable_if<!T::hasBar, int>::type>
struct getBar {
  static constexpr unsigned int bar = 0;
};

int main() {
  getBar<A>::bar; // Expect 20
  getBar<B>::bar; //Expect 0
}

I cannot compile this code with C++14. The compiler complains that: "template non-type parameter has a different type".

Why we have such an error and how can I address it?

like image 916
MTMD Avatar asked Jul 12 '26 06:07

MTMD


1 Answers

Class templates can't be overloaded (like function templates); You can use specialization instead. e.g.

template <typename T, typename = void>
struct getBar {
  static constexpr unsigned int bar = 0;
};

template <typename T>
struct getBar<T, std::enable_if_t<T::hasBar>> {
  static constexpr unsigned int bar = T::bar;
};

LIVE

like image 173
songyuanyao Avatar answered Jul 14 '26 19:07

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!