C++使用和typedef强类型

Jen*_*das 31 c++ c++14

在我们的项目中,我们使用了很多"使用"来明确说明应该表示的变量.它主要用于std::stringPortalId或者这样的识别器CakeId.现在我们目前可以做的是

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

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

portal_id = cake_id; // OK
Run Code Online (Sandbox Code Playgroud)

我们不喜欢.我们希望在编译期间进行类型检查,以防止我们混合苹果和橙子,同时保留原始对象中的大多数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;

}
Run Code Online (Sandbox Code Playgroud)

我们已经尝试了一些与模板结合使用的宏,但是没有得到我们所需要的.并补充 - 我们可以使用c ++ 14.

编辑:我们想出的代码是

#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; } \
};
Run Code Online (Sandbox Code Playgroud)

这是丑陋的,不起作用.并且它不起作用我的意思是编译器没问题portal_id = cake_id;.

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

Ric*_*ges 17

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

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是一个更新版本,也处理哈希映射,流式传输到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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您的解决方案很棒,但我会为 `_value` 类型添加第二个模板参数:http://ideone.com/IVlefk (2认同)
  • @Jendas ?? 它有10行完全类型安全,高效的代码,可以完全满足您的项目需求.它与我们在高度可扩展的生产服务器中使用的代码相同.但这当然取决于你:) (2认同)
  • *并且*它避免使用宏! (2认同)

kam*_*aze 12

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

#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>;
Run Code Online (Sandbox Code Playgroud)

  • @RichardHodges 你可以转换它们,但我不知道你会如何偶然地做到这一点。 (3认同)
  • 你是对的。string 的构造函数是显式的。好的。:) (2认同)

Jen*_*das 7

最近我遇到了一个名为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;
}
Run Code Online (Sandbox Code Playgroud)

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

需要注意的使用.emplace(..)方法,这是必要的,因为NamedType是由所需要的不是默认constructible []operator


Tar*_*ama 5

如果有一个标准的方法来做到这一点就好了,但目前还没有。将来可能会标准化一些东西:有一篇关于不透明类型定义的论文尝试使用函数别名和更丰富的继承构造来做到这一点,而一篇关于命名类型的论文则采用了一种更简单的方法,使用单个新关键字来引入强类型定义,或者无论你想怎么称呼它。

Boost Serialization 库提供的功能BOOST_STRONG_TYPEDEF可能会满足您的需求。

这是您的直接替代品SAFE_TYPEDEF,它BOOST_STRONG_TYPEDEF没有其他 boost 依赖项,并稍作修改,以便您无法从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; }   \
};
Run Code Online (Sandbox Code Playgroud)

Live Demo