【问题标题】:Strong typedefs [duplicate]强类型定义[重复]
【发布时间】:2015-05-09 02:40:06
【问题描述】:

有没有办法制作一个类型的完整副本,以便在模板推导上下文中区分它们?举个例子:

#include <iostream>

template <typename T>
struct test
{
    static int c()
    { 
        static int t = 0;
        return t++;
    }
};

typedef int handle;

int main()
{
    std::cout << test<int>::c() << std::endl;
    std::cout << test<handle>::c() << std::endl;
    return 0;
}

由于 typedef 只为类型创建别名,因此打印 0, 1 而不是所需的 0、0。有什么解决方法吗?

【问题讨论】:

标签: c++ templates type-deduction


【解决方案1】:

引用cplusplus.com

请注意,typedef 和 using 都不会创建新的不同数据类型。 它们只创建现有类型的同义词。 这意味着该类型 上面 myword 的,用 WORD 类型声明的,也可以考虑 输入无符号整数;这并不重要,因为两者实际上都是 指同一类型。

由于inthandle相同的,所以输出0 1 是预期的。

正如@interjay 建议的那样,有一个解决方法。

您可以使用BOOST_STRONG_TYPEDEF

BOOST_STRONG_TYPEDEF( int , handle );

【讨论】:

  • 问题是找到一个不会有这种行为的typedef 的替代品。
  • 语言中没有内置,但这并不意味着不能构建(例如我上面发布的链接)。
  • 是的,我知道 typedef 不能提供所需的行为。该链接看起来很有希望!
  • BOOST_STRONG_TYPEDEF 有两个问题。它不适用于用户定义的类型,并且在模板推导中不区分同一原语的多个 typedef。我写了一个解决这些问题的答案。
  • @shauryachats 实际上我想我在某个地方点击了错误。返回接受!
【解决方案2】:

按照建议的 BOOST_STRONG_TYPEDEF

template<typename>
struct test {
    static int c() {
        static int t = 0;
        return t++ ;
    } 
};

//Instead of 
//typedef int handle

BOOST_STRONG_TYPEDEF(int , handle) ;  

int main() {

    std::cout << test<int>::c() << std::endl
    std::cout << test<handle>::c() << std::endl ;
    return 0;
}

输出:0 0,因为句柄 不是 int 而是隐式可转换为 int 的类型。

如果您不想使用 BOOST_STRONG_TYPE 则只需添加第二个参数 到您的课程模板:

template<typename, unsigned int N>
struct test {
    static int c() {
        static int t = 0;
        return t++ ;
    }

};

从而使test&lt;int, 0&gt;test&lt;handle, 1&gt; 成为不同的类型

int main() {

    std::cout << test<int, 0>::c() << std::endl ;
    std::cout << test<handle,1>::c() << std::endl ;
    return 0;
} 

输出:0 0

您还可以添加宏来生成您的类型:

#define DEFINE_TEST_TYPE(type) \
typedef test<type, __COUNTER__> test_##type;


template<typename, unsigned int N>
struct test {    
     static int c() {
        static int t = 0;
        return t++ ;   
    }
};

typedef int handle ;

DEFINE_TEST_TYPE(int) ;
DEFINE_TEST_TYPE(handle) ;

int main() {
    std::cout << test_int::c() << std::endl ;
    std::cout << test_handle::c() << std::endl ;
    return 0;
}

【讨论】:

  • 关于你现在删除的关于你的开源项目的问题,你可以在相关的 Reddit 社区上提问。但是,如果您确实在多个 sub 中提出问题,请务必声明您的交叉发布,这样人们就可以避免重复回答。
猜你喜欢
  • 2022-01-18
  • 2014-09-16
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 2017-07-26
  • 2017-11-13
  • 2014-12-13
相关资源
最近更新 更多