在 C++ 中将 typedef 区分为相同类型 [英] Discriminating between typedefs to same type in c++

查看:24
本文介绍了在 C++ 中将 typedef 区分为相同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要类似于以下的功能:

I want functionality similar to the below:

typedef int A;
typedef int B;


struct foo
{
  foo(A a) { /*specific to type A*/ }
  foo(B b) { /*specific to type B*/ }
};

我在我的程序中使用 typedef 来表示相同类型在逻辑上的不同用法.所以,我想为不同的 typedef 以不同的方式创建 foo 类型的对象.我可以在 g++ 中编译它,但是 msvc 抛出一个合适的说法,当它看到第二个定义 foo(B) 时,已经定义了 foo(A).我想过使用类型列表和列表中类型的位置来区分类型定义并尝试使用 boost::mpl::vector:

I use the typedefs in my program to denote logically different usage of the same type. So, I would like to create object of type foo differently for different typedefs. I could compile this in g++, but msvc throws a fit saying that foo(A) is already defined when it sees the second definition foo(B). I thought of using a type list and the position of a type in the list to discriminate between the typedefs and tried using a boost::mpl::vector:

#include <boost/mpl/vector.hpp >
#include <boost/mpl/find.hpp>

typedef int A;
typedef int B;


struct foo
{
     typedef boost::mpl::vector<A, B> supported_types;

     foo(boost::mpl::find<supported_types, A>::type, A a) {}
     foo(boost::mpl::find<supported_types, B>::type, B b) {}
};

但不幸的是,在这两种情况下, find 也丢弃了我的 typedef 并且只返回 A 的迭代器.我还想过定义一个枚举并为每种类型使用它

but unfortunately, find too discards my typedef and just returns iterator for A in both cases. I also thought about defining an enum and using it for each type

enum { TYPE_A, TYPE_B };
template <int i> struct int2type {};

并在程序中使用这个 int2type 和类型 B.但这对我来说看起来不雅,因为它容易出错.我想使用类型列表并执行此操作,以便明确支持哪些类型.

and using this int2type and type B in the program. But this looks inelegant to me as it is prone to errors. I would like use a typelist and do this, so that it is clear what types would be supported.

请告诉我是否有一种通用且可扩展的方法来做到这一点.

Please let me know if there is a generic and extensible way of doing this.

推荐答案

A boost strong typedef 应该做你想要的.

A boost strong typedef should do what you're looking for.

#include <boost/strong_typedef.hpp>

BOOST_STRONG_TYPEDEF(int, A);
BOOST_STRONG_TYPEDEF(int, B);

这篇关于在 C++ 中将 typedef 区分为相同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆