gpt4 book ai didi

c++ - 对齐是否与指向模板对象的指针有关? (C++)

转载 作者:行者123 更新时间:2023-11-28 02:44:47 24 4
gpt4 key购买 nike

我正在使用模板嵌套类来存储类型。该类没有数据成员,但它确实有返回 bool 作为 type_traits 比较结果的模板方法。

// Someheader.h
#include < new >
#include < type_traits >

// ...

class foo {

private:

template < typename T >
class bar {

public:

bar ( ) { }
~bar ( ) { }

template < typename U >
bool convertible_to ( const U& hint ) {

return std::is_convertible < T, U > :: value;
}

template < typename U >
bool convertible_from ( const U& hint ) {

return std::is_convertible < U, T > :: value;
}

};

bar < void >* helper;

public:

foo ( ) { }
~foo ( ) { delete helper; } // Correction from Kerrek SB here.

template < typename T >
foo ( const T& hint ) :
helper ( &( ::new ( helper ) bar < T > ( ) ) )
{}

template < typename U >
bool convertible_to ( const U& hint ) {

return helper -> convertible_to ( hint );
}

template < typename U >
bool convertible_from ( const U& hint ) {

return helper -> convertible_from ( hint );
}
};

我有点担心我对 placement new 的使用。类 bar 没有数据成员,但我不知道指针对齐是否是模板类型的问题。假设 T = int,并且 int 需要一些对齐 n * 2^m。指向模板类型为 int 的模板对象的指针是否会继承该要求?

我似乎找不到关于这个主题的任何内容,如果这是一个愚蠢的问题,我深表歉意。

最佳答案

对齐并不重要,因为您从不直接使用类型。但是,此代码根本无法按您期望的方式工作。它将始终调用 foo::bar<void>::convertable_tofoo::bar<void>::convertable_from .另外,它不是类型安全的。

关于c++ - 对齐是否与指向模板对象的指针有关? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com