2016-09-19 3 views
1

私は、ポインタの最下位ビットがフラグとして利用可能なタグ付きポインタクラスを設計しようとしていますが、実際に利用可能な場合、つまり、タイプが1より大きい。alignofに基づくタグ付きポインタの特殊化

最後の問題を除いて、alignof()を不完全型に適用できない場合を除き、次のように動作します。

#include <cstdint> //for std::uintptr_t 

template<typename T> struct always_tagged_pointer { 
    static_assert(alignof(T) != 1, ""); //lsb available 
    union { T* ptr; std::uintptr_t bits; }; 
    //rest of implementation omitted 
}; 
template<typename T, size_t alignof_T> struct maybe_tagged_pointer_impl { 
    static_assert(alignof(T) != 1, ""); //lsb available 
    union { T* ptr; std::uintptr_t bits; }; 
    //rest of implementation omitted 
}; 
template<typename T> struct maybe_tagged_pointer_impl<T, 1> { 
    static_assert(alignof(T) == 1, ""); //lsb not available 
    T* ptr; bool flag; 
    //rest of implementation omitted 
}; 
template<typename T> using maybe_tagged_pointer = maybe_tagged_pointer_impl<T, alignof(T)>; 

maybe_tagged_pointer<int> a; //OK. 
maybe_tagged_pointer<char> b; //OK. 

struct foo { 
    int i; //so that alignof(foo)!=1 for this test 
    void fun1(always_tagged_pointer<foo> p) {} //Ok. 
    void fun2(maybe_tagged_pointer<foo> p) {} //error: invalid application of 'alignof' to an incomplete type 'foo' 
}; 

私が欲しいものを達成する方法はありますか?おそらく別のデザインですか?

+0

アラインメントとメモリの場所は異なる懸念事項です(偶数アラインメントタイプは奇数アドレスに格納される可能性があります)。 –

+0

'foo'の外で' fun2'を動かすことはできませんか? – Jarod42

+0

@DieterLückingこのようなプラットフォームや実装を設計するエンジニアは、長い間生き残る傾向がありません。 –

答えて

0

この「リラックス」アプローチはあなたに適していますか?

struct foo { 
    int i; //so that alignof(foo)!=1 for this test 
    void fun1(always_tagged_pointer<foo> p) {} //Ok. 
    // with the discipline that the calling code will always pass a foo 
    // for the U type, this may work 
    template <type U> void fun2(maybe_tagged_pointer<U> p) { 
     // will this create one more compile err?? 
     using dummy_t=std::enable_if<std::is_same<U,foo>::value> 
    } 
}; 
+0

おそらく、コンパイル時のアサートでこの規律を強制することができます: 'static_assert(std :: is_same :: value、" ... ");'? – piwi

+0

'テンプレート std :: enable_if_t > fun2(..)'は他のオプションになります。 – Jarod42

関連する問題