gpt4 book ai didi

c++ - 如何在 `operator==` 包装类中使用重载 `std::variant` 来比较 Setting Vs Setting 和 T vs T?

转载 作者:行者123 更新时间:2023-12-04 00:12:50 25 4
gpt4 key购买 nike

我正在尝试为围绕 std::variant 的包装类编写模板化的 operator==。这个想法是 Setting 类与其他 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_ 成员变量(Setting设置)。

#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;
}

最佳答案

你有一个错字;您正在调用std::getsetting参数,而不是 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”,我将实现推到一个静态强制向下转换的父类中,以及 Koenig 或 ADL 友元运算符,这让我可以注入(inject)非模板 operator==进入 Setting == something 的查找参与重载决议。

Live example .

现在这还不错,但它遇到了一个问题,它将事物转换T .所以SettingT<std::string> == "hello"熄灭并创建一个 std::string然后放 "hello"在其中,然后比较 std::stringSettingT进入它。

真的,我们只想发送 "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并返回该类型,然后我们发送到 ==无需先进行转换。

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

Live example .

关于c++ - 如何在 `operator==` 包装类中使用重载 `std::variant` 来比较 Setting Vs Setting 和 T vs T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67374983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com