Strong typedefs

Strong typedefs

本文关键字:typedefs Strong      更新时间:2023-10-16

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

#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。对此有什么变通办法吗?

报价cplusplus.com,

请注意,既不使用typedef也不使用创建新的不同数据类型。它们只创建现有类型的同义词这意味着上面用WORD类型声明的myword的键入unsigned int;这其实并不重要,因为两者都是指的是相同的类型。

由于inthandle一个且相同的,因此预期输出0 1

不过,正如@interjay所建议的,有一个变通办法。

您可以使用BOOST_STRONG_TYPEDEF

BOOST_STRONG_TYPEDEF( int , handle );

按照建议BOOstrongTRONG_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的类型。

如果您不想使用BOOstrongTRONG_TYPE,那么只需添加第二个参数到你的课堂模板:

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

从而使test<int, 0>test<handle, 1>成为不同类型的

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