gpt4 book ai didi

c++ - 强类型使用和 typedef

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:27 25 4
gpt4 key购买 nike

在我们的项目中,我们使用了很多“用法”来明确说明变量应该表示什么。它主要用于 std::string 标识符,如 PortalIdCakeId。现在我们目前能做的是

using PortalId = std::string;
using CakeId = std::string;

PortalId portal_id("2");
CakeId cake_id("is a lie");

portal_id = cake_id; // OK

我们不喜欢。我们希望在编译时进行类型检查,以防止我们在保留原始对象的大部分 yum yum 方法的同时将苹果和橘子混合在一起。

所以问题是 - 这是否可以在 C++ 中完成,以便用法接近于以下内容,赋值会失败,但我们仍然可以将它与 map 和其他容器一起使用?

SAFE_TYPEDEF(std::string, PortalId);
SAFE_TYPEDEF(std::string, CakeId);

int main()
{
PortalId portal_id("2");
CakeId cake_id("is a lie");
std::map<CakeId, PortalId> p_to_cake; // OK

p_to_cake[cake_id] = portal_id; // OK
p_to_cake[portal_id] = cake_id; // COMPILER ERROR

portal_id = cake_id; // COMPILER ERROR
portal_id = "1.0"; // COMPILER ERROR
portal_id = PortalId("42"); // OK
return 0;

}

我们已经尝试过将宏与模板结合使用,但并没有完全满足我们的需求。并添加 - 我们可以使用 c++17。

编辑:我们想出的代码是

#define SAFE_TYPEDEF(Base, name) \
class name : public Base { \
public: \
template <class... Args> \
explicit name (Args... args) : Base(args...) {} \
const Base& raw() const { return *this; } \
};

这很丑陋 并且不起作用。它不起作用,我的意思是编译器可以使用 portal_id = cake_id;

EDIT2: 添加了 explicit 关键字,我们的代码实际上可以很好地用于我们的示例。不确定这是否是正确的方法以及它是否涵盖所有不幸的情况。

最佳答案

这是一个最小的完整解决方案,可以满足您的需求。

您可以根据需要添加更多运算符等以使该类更有用。

#include <iostream>
#include <string>
#include <map>

// define some tags to create uniqueness
struct portal_tag {};
struct cake_tag {};

// a string-like identifier that is typed on a tag type
template<class Tag>
struct string_id
{
// needs to be default-constuctable because of use in map[] below
string_id(std::string s) : _value(std::move(s)) {}
string_id() : _value() {}

// provide access to the underlying string value
const std::string& value() const { return _value; }
private:
std::string _value;

// will only compare against same type of id.
friend bool operator < (const string_id& l, const string_id& r) {
return l._value < r._value;
}
};


// create some type aliases for ease of use
using PortalId = string_id<portal_tag>;
using CakeId = string_id<cake_tag>;

using namespace std;

// confirm that requirements are met
auto main() -> int
{
PortalId portal_id("2");
CakeId cake_id("is a lie");
std::map<CakeId, PortalId> p_to_cake; // OK

p_to_cake[cake_id] = portal_id; // OK
// p_to_cake[portal_id] = cake_id; // COMPILER ERROR

// portal_id = cake_id; // COMPILER ERROR
// portal_id = "1.0"; // COMPILER ERROR
portal_id = PortalId("42"); // OK
return 0;
}

这是一个更新版本,它还可以处理 HashMap 、流式传输到 ostream 等。

您会注意到我没有提供转换为 string 的运算符。这是故意的。我要求此类的用户通过提供 to_string 的重载来明确表达将其用作字符串的意图。

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>

// define some tags to create uniqueness
struct portal_tag {};
struct cake_tag {};

// a string-like identifier that is typed on a tag type
template<class Tag>
struct string_id
{
using tag_type = Tag;

// needs to be default-constuctable because of use in map[] below
string_id(std::string s) : _value(std::move(s)) {}
string_id() : _value() {}

// provide access to the underlying string value
const std::string& value() const { return _value; }
private:
std::string _value;

// will only compare against same type of id.
friend bool operator < (const string_id& l, const string_id& r) {
return l._value < r._value;
}

friend bool operator == (const string_id& l, const string_id& r) {
return l._value == r._value;
}

// and let's go ahead and provide expected free functions
friend
auto to_string(const string_id& r)
-> const std::string&
{
return r._value;
}

friend
auto operator << (std::ostream& os, const string_id& sid)
-> std::ostream&
{
return os << sid.value();
}

friend
std::size_t hash_code(const string_id& sid)
{
std::size_t seed = typeid(tag_type).hash_code();
seed ^= std::hash<std::string>()(sid._value);
return seed;
}

};

// let's make it hashable

namespace std {
template<class Tag>
struct hash<string_id<Tag>>
{
using argument_type = string_id<Tag>;
using result_type = std::size_t;

result_type operator()(const argument_type& arg) const {
return hash_code(arg);
}
};
}


// create some type aliases for ease of use
using PortalId = string_id<portal_tag>;
using CakeId = string_id<cake_tag>;

using namespace std;

// confirm that requirements are met
auto main() -> int
{
PortalId portal_id("2");
CakeId cake_id("is a lie");
std::map<CakeId, PortalId> p_to_cake; // OK

p_to_cake[cake_id] = portal_id; // OK
// p_to_cake[portal_id] = cake_id; // COMPILER ERROR

// portal_id = cake_id; // COMPILER ERROR
// portal_id = "1.0"; // COMPILER ERROR
portal_id = PortalId("42"); // OK

// extra checks

std::unordered_map<CakeId, PortalId> hashed_ptocake;
hashed_ptocake.emplace(CakeId("foo"), PortalId("bar"));
hashed_ptocake.emplace(CakeId("baz"), PortalId("bar2"));

for(const auto& entry : hashed_ptocake) {
cout << entry.first << " = " << entry.second << '\n';

// exercise string conversion
auto s = to_string(entry.first) + " maps to " + to_string(entry.second);
cout << s << '\n';
}

// if I really want to copy the values of dissimilar types I can express it:

const CakeId cake1("a cake ident");
auto convert = PortalId(to_string(cake1));

cout << "this portal is called '" << convert << "', just like the cake called '" << cake1 << "'\n";


return 0;
}

关于c++ - 强类型使用和 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439366/

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