如何在 `std::variant` 包装器 class 中使用重载 `operator==` 来比较设置与设置以及 T 与 T?

How to use overload `operator==` in a `std::variant` wrapper class to make comparisons between Setting Vs Setting and T vs T?

我正在尝试为围绕 std::variant 的包装器 class 编写模板 operator==。这个想法是 Setting class 与其他 Setting 对象以及变体支持的类型是可比较的。我已经在没有模板的情况下解决了这个问题,因为它很容易写出 operators==,但是学习模板方法对我来说很重要。

所以,这就是我希望使用 Setting 的方式:

Setting s1("string");
Setting s2("string");
s1 == s2; // okay, equals true

以及

Setting s3("string");
s3 == "string"; // should equal true
std::string s4 = "string";
s3 == s4; // also True

这是我到目前为止所了解的,尽管我很确定我还有很长的路要走。该策略是对 operator= 进行模板化,这样如果模板参数 T 是有效的变体 (setting_t) 类型,则从变体中提取值作为类型 T并进行比较(TT 进行比较)。或者,当 T 是另一个 Setting 时,我们可以直接比较 setting_ 成员变量(SettingSetting 比较)。

#include <type_traits>
#include <variant>

using setting_t = std::variant<std::string, int, double>;

/**
 * Utility which is true when
 * type T is in a variant, false otherwise.
 * For instance,
 *  std::string x("a String");
 *  bool truth = isValidVariantType<decltype(x), setting_t>(); // true
 *  
 *  unsigned long x = 4;
 *  bool truth = isValidVariantType<decltype(x), setting_t>(); // false
 */
template<typename T, typename ALL_T>
struct isValidVariantType;

template<typename T, typename... ALL_T>
struct isValidVariantType<T, std::variant<ALL_T...>>
        : public std::disjunction<std::is_same<T, ALL_T>...> {
};

class Setting {
public:
    explicit Setting(setting_t setting)
            : setting_(std::move(setting)) {}

    template <typename T,
            class = typename std::enable_if<isValidVariantType<T, setting_t>::value>::type>
    bool operator==(const T& setting){
        T val = std::get<T>(setting);
        return val == setting;
    }

private:
    setting_t setting_;
};

我现在已经在这上面花了很多时间,所以我很感激你能给我的任何建议。提前谢谢!

编辑 - 编译器错误

根据要求,这是编译器当前生成的内容

当我运行SettingTests.SettingVsSetting

TEST(SettingTests, SettingVsSetting){
    Setting setting1("a String");
    Setting setting2("a String");
//    bool truth = setting1 == setting2;
}

生成以下编译器消息:

/home/ciaran/SettingTests/SRC/TemplateTutorialTests.cpp: In member function ‘virtual void SettingTests_SettingVsSetting_Test::TestBody()’:
/home/ciaran/SettingTests/SRC/TemplateTutorialTests.cpp:11:27: error: no match for ‘operator==’ (operand types are ‘Setting’ and ‘Setting’)
   11 |     bool truth = setting1 == setting2;
      |                  ~~~~~~~~ ^~ ~~~~~~~~
      |                  |           |
      |                  Setting     Setting
In file included from /home/ciaran/SettingTests/SRC/TemplateTutorialTests.cpp:2:
/home/ciaran/SettingTests/SRC/TermplateTutorial.hpp:32:10: note: candidate: ‘template<class T, class> bool Setting::operator==(const T&)’
   32 |     bool operator==(const T& setting){
      |          ^~~~~~~~
/home/ciaran/SettingTests/SRC/TermplateTutorial.hpp:32:10: note:   template argument deduction/substitution failed:
/home/ciaran/SettingTests/SRC/TermplateTutorial.hpp:31:13: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
   31 |             class = typename std::enable_if<isValidVariantType<T, setting_t>::value>::type>
      |             ^~~~~

同时 Setting.SettingVsString

TEST(SettingTests, SettingVsString){
    Setting setting1("a String");
    std::string setting2("a String");
    bool truth = setting1 == setting2;
}

生成

/home/ciaran/SettingTests/SRC/TermplateTutorial.hpp: In instantiation of ‘bool Setting::operator==(const T&) [with T = std::__cxx11::basic_string<char>; <template-parameter-1-2> = void]’:
/home/ciaran/SettingTests/SRC/TemplateTutorialTests.cpp:17:30:   required from here
/home/ciaran/SettingTests/SRC/TermplateTutorial.hpp:33:28: error: no matching function for call to ‘get<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(const std::__cxx11::basic_string<char>&)’
   33 |         T val = std::get<T>(setting);
      |                 ~~~~~~~~~~~^~~~~~~~~
In file included from /usr/include/c++/10/bits/unique_ptr.h:36,
                 from /usr/include/c++/10/memory:83,
                 from /home/ciaran/SettingTests/googletest/googletest/include/gtest/gtest.h:57,
                 from /home/ciaran/SettingTests/SRC/TemplateTutorialTests.cpp:1:
/usr/include/c++/10/utility:223:5: note: candidate: ‘template<long unsigned int _Int, class _Tp1, class _Tp2> constexpr typename std::tuple_element<_Int, std::pair<_Tp1, _Tp2> >::type& std::get(std::pair<_Tp1, _Tp2>&)’
  223 |     get(std::pair<_Tp1, _Tp2>& __in) noexcept
      |     ^~~
/usr/include/c++/10/utility:223:5: note:   template argument deduction/substitution failed:
/usr/include/c++/10/utility:228:5: note: candidate: ‘template<long unsigned int _Int, class _Tp1, class _Tp2> constexpr typename std::tuple_element<_Int, std::pair<_Tp1, _Tp2> >::type&& std::get(std::pair<_Tp1, _Tp2>&&)’
  228 |     get(std::pair<_Tp1, _Tp2>&& __in) noexcept
      |     ^~~

... (it goes on like this for a while)

编辑 3 - 备选方案 operator==

    template<typename T,
            class = typename std::enable_if<isValidVariantType<T, setting_t>::value>::type>
    bool operator==(const T &setting) {
        if (auto val = std::get_if<T>(&setting_)){
            return *val == setting;
        };
        return false;
    }

你打错了;您在 setting 参数上调用 std::get,而不是 this->setting_。修复使您的代码编译。

但你可以做得更好。

template<class D, class T>
class SettingEqual {
    D const& self() const { return *static_cast<D const*>(this); }
    D & self() { return *static_cast<D*>(this); }
    decltype(auto) setting() { return self().setting_; }
    decltype(auto) setting() const { return self().setting_; }

    friend bool operator==( SettingEqual const& self, T const& t ) {
      if (!std::holds_alternative<T>(self.setting())) return false;
      return std::get<T>(self.setting()) == t;
    }
    friend bool operator==( T const& t, SettingEqual const& self ) {
      return (self==t);
    }
    friend bool operator!=( T const& t, SettingEqual const& self ) {
      return !(self==t);
    }
    friend bool operator!=( SettingEqual const& self, T const& t ) {
      return !(self==t);
    }
};
template<class...Ts>
class SettingT:
    public SettingEqual<SettingT<Ts...>, Ts>...
{
    template<class D, class T>
    friend class SettingEqual;
public:
    explicit SettingT(std::variant<Ts...> setting)
            : setting_(std::move(setting)) {}

private:
    std::variant<Ts...> setting_;
};
using Setting = SettingT<std::string, int, double>;

这在左侧和右侧引入了 ==!= 重载,它们参与了重载解析。

它还会检查类型是否匹配,并表示不匹配的类型不相等。

使用的技术是“CRTP”,其中我将实现推到父级 class 中,静态转换向下转换,以及 Koenig 或 ADL 友元运算符,这让我可以注入非模板 operator==进入 Setting == something 的查找以参与重载决议。

Live example.

现在这还不错,但它遇到了问题,即它 转换为 T。所以 SettingT<std::string> == "hello" 关闭并创建一个 std::string 然后将 "hello" 放入其中,然后将 SettingT 中的 std::string 比较到其中。

真的,我们只想将 "hello" 直接发送到 std::string==,或者做一些更好的事情。

template<class T>
struct tag_t {using type=T;};
template<class T>
constexpr tag_t<T> tag{};

template<class T>
struct overload_detect {
  auto operator()(T const&){return tag<T>;};
};
template<class...Ts>
struct overload_detector:overload_detect<Ts>... {
  using overload_detect<Ts>::operator()...;
};
template<class T0, class...Ts>
using best_conversion = typename decltype(overload_detector<Ts...>{}( std::declval<T0 const&>() ))::type;
template<class T, class...Ts>
concept any_conversion = requires (T a) {
    { (std::void_t<best_conversion<T, Ts...>>)(0) };
};

template<class...Ts>
class SettingT
{
public:
    explicit SettingT(std::variant<Ts...> setting)
            : setting_(std::move(setting)) {}
    template<any_conversion<Ts...> U>
    friend bool operator==(SettingT const& self, U const& u) {
        using T = best_conversion<U, Ts...>;
        if (!std::holds_alternative<T>(self.setting_)) return false;
        return std::get<T>(self.setting_) == u;
    }
    template<any_conversion<Ts...> U>
    friend bool operator==(U const& u,SettingT const& self) {
        return self==u;
    }
    template<any_conversion<Ts...> U>
    friend bool operator!=(U const& u,SettingT const& self) {
        return !(self==u);
    }
    template<any_conversion<Ts...> U>
    friend bool operator!=(SettingT const& self, U const& u) {
        return !(self==u);
    }
private:
    std::variant<Ts...> setting_;
};

现在 best_conversion<X, Ys...>Ys 中找到 X 和 returns 那种类型的最佳转换,我们在没有先做转换。

== 可以自由地进行转换,或者如果它愿意,它可以做一些更有效率的事情。

Live example.