Warm tip: This article is reproduced from stackoverflow.com, please click
c++ googletest sfinae

Is this a bug in GoogleTest AssertionResult?

发布于 2020-03-31 22:57:43

I've trimmed down the EXPECT_TRUE macro from gtest.h.

#include <type_traits>
#include <iostream>

class rai_class {
    public:
        static bool const value = true;
};

class AssertionResult {
 public:
  template <typename T>
  explicit AssertionResult(
      const T& success,
      typename std::enable_if<
          !std::is_convertible<T, AssertionResult>::value>::type*
          = nullptr)
      : success_(success) {}

  operator bool() const { return success_; }
 private:
  bool success_;
};

// Test type trait
bool test_rai_hash_implemented()
{
    return AssertionResult(rai_class::value);
    //return rai_class::value;
}

int main()
{
    std::cout << test_rai_hash_implemented() << "\n";
    return 0;
}

Without optimisations, it produces the link error "undefined reference to `rai_class::value'".

With -O2 it works ok. Any ideas what's going on?

Questioner
Rai
Viewed
17
Jarod42 2020-01-31 22:56

rai_class::value is ODR-used (through const T& success), and so requires a definition.

bool const rai_class::value;

Demo

or use constexpr (which is implicitly inline since C++17)

class rai_class {
public:
    static bool constexpr value = true;
};

Demo