在编译时确保模板类型的一致性

Jas*_*n S 3 c++ templates typedef

我有这个模板类:

template <class Tin, class Tout>
class Foo
{
    Tin input;
    Tout output;

    static inline void __ensure_type_consistency
    {
        int16_t* p = (int16_t *)0;
        // uint16_t* p1 = p;
        Tin* check_type_in = p;
        Tout* check_type_out = p;  
    }
public:
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想,以确保TinTout都是typedef定义为类型int16_t而不是其他类型.(注意: 在得出结论之前请先阅读完整的问题)

如果我取消注释注释行,我会收到预期的错误; 编译器不允许在没有强制转换的情况下将不同类型的指针分配给彼此:

"src\foo.h", line 47: error #145: a value of type "int16_t *" 
cannot be used to initialize an entity of type "uint16_t *"
Run Code Online (Sandbox Code Playgroud)

但如果我把它注释掉,我会实例化:

Foo<uint16_t, int32_t> illegalFoo;
Run Code Online (Sandbox Code Playgroud)

我没有得到编译器错误,即使使用了相同类型的检查(在静态函数中创建一个不兼容的指针赋值,该函数从未实际调用,但应该导致编译器错误)

有没有办法创建静态编译时类型一致性检查?为什么我使用的那个不起作用?

注意:忽略一下只是摆脱模板参数的明显解决方案.这将"解决"这个问题,但也有一些出带外的事情与我的调试工具怎么回事,其中的typedef被用来传授重要的元数据:我想确保Foo.input的类型的Tin地方Tin或者是一个int16_t或一个typedef解析作为int16_t,并类似地与Foo.outputTout.从我的调试工具的角度来看,存在细微差别,其中可以区分typedef类型及其基类型,即使在C++程序中它们是相同的.


编辑:顺便说一句,这是一个嵌入式系统,我不能使用Boost.它也不是C++ 0x.

Jam*_*lis 5

您可以is_same在a中使用类型特征static_assert.C++ 0x看起来像:

static_assert(std::is_same<Tin, std::int16_t>::value &&
              std::is_same<Tout, std::int16_t>::value, "o noez");
Run Code Online (Sandbox Code Playgroud)

你可以找到两者is_same类型特征静态断言在升压为好.即使您正在为嵌入式系统进行编译,也可以直接从Boost中提取类型特征和静态断言头,并且这些库都没有任何运行时开销.