【问题标题】:Strongly typed using and typedef强类型 using 和 typedef
【发布时间】:2016-03-21 03:53:22
【问题描述】:

在我们的项目中,我们使用了很多“使用”来明确说明变量应该代表什么。它主要用于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++ 中完成,这样使用将接近以下内容,分配会失败,我们仍然可以将它与地图和其他容器一起使用?

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 关键字,我们的代码实际上可以很好地用于我们的示例。不确定这是否是正确的方法以及是否涵盖所有不幸的情况。

【问题讨论】:

  • 只需在 c-tor 之前添加显式即可。
  • 如果你对字符串这样做,使用该类型很容易导致未定义的行为:SAFE_TYPEDEF(std::string, S); std::string* s = new S(); delete s; std::string 不打算用作基类。
  • portal_id = cake_id 有效,因为有了这个构造,CakeID 可以传递到任何需要字符串的地方——例如传递给PortalId 的赋值运算符。继承定义了一种“是一种”关系。
  • 使用隐含定义操作的简洁语法定义新类型的问题在于,并非所有操作都与这些不同类型相关,具体取决于只能由程序员详细描述的意图。

标签: c++ c++14 c++17


【解决方案1】:

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

您可以添加更多运算符等,以使该类在您认为合适的时候更有用。

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

这是一个更新版本,它还可以处理哈希映射、流式传输到 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;
}

【讨论】:

  • 您的解决方案很棒,但我会为 _value 类型添加第二个模板参数:ideone.com/IVlefk
  • @Jendas ??它是 10 行完美类型安全、高效的代码,可以完全满足您的项目需求。它与我们在高度可扩展的生产服务器中使用的代码相同。但这当然取决于你:)
  • 而且它避免使用宏!
  • 打字比int main() 还要多,而且……毫无意义?
  • @S.S.Anne 一切都毫无意义:) - 老实说,这些天我使用尾随返回类型来保持一致性。除了习惯之外,我没有出于任何特殊原因这样做。
【解决方案2】:

到目前为止提供的解决方案似乎过于复杂,所以这是我的尝试:

#include <string>

enum string_id {PORTAL, CAKE};

template <int ID> class safe_str : public std::string {
    public:
    using std::string::string;
};

using PortalId = safe_str<PORTAL>;
using CakeId = safe_str<CAKE>;

【讨论】:

  • 这种方法的问题是不同类型的safe_str都是从字符串公开派生的。因此,它们可以相互转换。这意味着 safe_str 实际上根本不安全。
  • @RichardHodges 你可以转换它们,但我不知道你会怎么做。
  • 你是对的。字符串的构造函数是显式的。好的。 :)
  • @RichardHodges 哪个构造函数是显式的?
  • @RichardHodges 在传统 C++ 中,只有将一个参数 ctors(不是复制 ctors)声明为显式才有意义,因为 没有其他情况下构造函数声明会创建隐式转换。 (在现代 C++ 中有大括号 init,因此略有不同。)
【解决方案3】:

最近我遇到了一个名为NamedTypes 的库,它提供了包装精美的语法糖来完全满足我们的需要!使用该库,我们的示例将如下所示:

namespace fl = fluent;
using PortalId = fl::NamedType<std::string, struct PortalIdTag>;
using CakeId = fl::NamedType<std::string, struct CakeIdTag, fl::Comparable>;

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

    p_to_cake.emplace(cake_id, portal_id); // OK
    // p_to_cake.emplace(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;
}

NamedTypes 库提供了更多附加属性,例如PrintableIncrementableHashable 等,您可以使用它们来创建例如数组和类似的强类型索引。有关更多详细信息,请参阅链接的存储库。

注意.emplace(..) 方法的使用,这是必要的,因为NamedType 不是[]operator 要求的默认可构造函数。

【讨论】:

    【解决方案4】:

    如果有标准的方法来做到这一点,那就太好了,但目前还没有。将来可能会标准化一些东西:有一篇关于Opaque Typedefs 的论文尝试使用函数别名和更丰富的继承结构来做到这一点,还有一篇关于Named Types 的论文采用了一种更简单的方法,使用一个新关键字来引入一个强大的typedef,或者任何你想叫它的名字。

    Boost 序列化库提供了BOOST_STRONG_TYPEDEF,它可能会给你想要的东西。

    这是您的 SAFE_TYPEDEF 的直接替换,它只是 BOOST_STRONG_TYPEDEF,没有其他提升依赖项,并且稍作修改,以便您无法从 typedefd 类型分配。我还添加了一个移动构造函数和赋值运算符,并使用了default

    namespace detail {
        template <typename T> class empty_base {};
    }
    
    template <class T, class U, class B = ::detail::empty_base<T> >
    struct less_than_comparable2 : B
    {
         friend bool operator<=(const T& x, const U& y) { return !(x > y); }
         friend bool operator>=(const T& x, const U& y) { return !(x < y); }
         friend bool operator>(const U& x, const T& y)  { return y < x; }
         friend bool operator<(const U& x, const T& y)  { return y > x; }
         friend bool operator<=(const U& x, const T& y) { return !(y < x); }
         friend bool operator>=(const U& x, const T& y) { return !(y > x); }
    };
    
    template <class T, class B = ::detail::empty_base<T> >
    struct less_than_comparable1 : B
    {
         friend bool operator>(const T& x, const T& y)  { return y < x; }
         friend bool operator<=(const T& x, const T& y) { return !(y < x); }
         friend bool operator>=(const T& x, const T& y) { return !(x < y); }
    };
    
    template <class T, class U, class B = ::detail::empty_base<T> >
    struct equality_comparable2 : B
    {
         friend bool operator==(const U& y, const T& x) { return x == y; }
         friend bool operator!=(const U& y, const T& x) { return !(x == y); }
         friend bool operator!=(const T& y, const U& x) { return !(y == x); }
    };
    
    template <class T, class B = ::detail::empty_base<T> >
    struct equality_comparable1 : B
    {
         friend bool operator!=(const T& x, const T& y) { return !(x == y); }
    };
    
    template <class T, class U, class B = ::detail::empty_base<T> >
    struct totally_ordered2
        : less_than_comparable2<T, U
        , equality_comparable2<T, U, B
          > > {};
    
    template <class T, class B = ::detail::empty_base<T> >
    struct totally_ordered1
        : less_than_comparable1<T
        , equality_comparable1<T, B
          > > {};
    
    #define SAFE_TYPEDEF(T, D)                                      \
    struct D                                                        \
        : totally_ordered1< D                                       \
        , totally_ordered2< D, T                                    \
        > >                                                         \
    {                                                               \
        T t;                                                        \
        explicit D(const T& t_) : t(t_) {};                         \
        explicit D(T&& t_) : t(std::move(t_)) {};                   \ 
        D() = default;                                              \
        D(const D & t_) = default;                                  \
        D(D&&) = default;                                           \
        D & operator=(const D & rhs) = default;                     \
        D & operator=(D&&) = default;                               \
        operator T & () { return t; }                               \
        bool operator==(const D & rhs) const { return t == rhs.t; } \
        bool operator<(const D & rhs) const { return t < rhs.t; }   \
    };
    

    Live Demo

    【讨论】:

    • 啊,命名类型,这个词我记不得了。
    • 我也很惊讶命名类型还没有在 c++14 中引入。
    • 猜反对票是因为我没有提供完整的解决方案?现在有一个。
    • 这个解决方案是从 boost 中解除的吗?如果是这样,我认为它需要查看,因为它通过不提供移动构造函数和赋值而违反了 5 规则。
    • @RichardHodges 是的,正如我所说,这是从 Boost 中提取的,只是做了一些小的改动。看起来大部分都可以使用defaulted 特殊成员。
    猜你喜欢
    • 2012-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多