加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:28:39 所属栏目:百科 来源:网络整理
导读:我有这个模板类: template class Tin,class Toutclass 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: ...}
我有这个模板类:

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:
    ...
}

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

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

"srcfoo.h",line 47: error #145: a value of type "int16_t *" 
cannot be used to initialize an entity of type "uint16_t *"

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

Foo<uint16_t,int32_t> illegalFoo;

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

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

注意:忽略一下只是摆脱模板参数的明显解决方案.这将“解决”这个问题,但是我的调试工具有一些带外的事情,其中??typedef用于传递重要的元数据:我想确保Foo.input的类型是Tin,其中Tin是int16_t或typedef,解析为int16_t,类似于Foo.output和Tout.从我的调试工具的角度来看,存在细微差别,其中可以区分typedef类型及其基类型,即使在C程序中它们是相同的.

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

解决方法

一个简单的方法:

template <class,class> class Foo;

template <>
class Foo<int16_t,int16_t> {
  ...
};

另一方面,如果您的条件实际上更复杂,则使用来自Boost的BOOST_STATIC_ASSERT或来自C 0x的static_assert.既然你想要非Boost选项并且C 0x可能不起作用,这里的内容更类似于你在例子中发布的内容:

(void)(true ? (int16_t**)0 : (Tin**)0);

和Tout相同.这需要在一些方法中被调用或者具有其地址(这样做的习惯是在the Boost.Concept_check implementation documentation结束时).如果你想要其他人发布但没有Boost或C 0x的is_same / static_assert解决方案,请尝试:

template <class,class> struct types_valid {static const int value = -1;};
template <> struct types_valid<int16_t,int16_t> {static const int value = 1;};

然后把静态字符foo [types_valid< Tin,Tout> :: value];在你的班级以外的任何方法.我相信你不需要实际定义foo,只要你不在任何地方引用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读