次のようなクラスがあり、クラステンプレートTによって '->'演算子を特殊化したいと思います。特殊化は、型Tがポインタ型であるかどうかによって異なります。私は解決策を探しましたが、この特定の問題については何も見つかりませんでした。
template <typename T>
class C
{
public:
// when T is a pointer type
T operator->()
{
return value;
}
// when T is not a pointer type
const T* operator->() const
{
return &value;
}
private:
T value;
};
void test()
{
struct Test
{
int x, y;
};
C<Test> c1;
C<Test*> c2;
c1->x = 5; // should both work
c2->x = 5; // ignoring the fact, that c2's value is undefined
}
助けてくれてありがとう!
あなたは必要な部分特殊化をし、また、あなたはポインタを逆参照して注意する必要があります。元の例はクラッシュする可能性があります。
template <typename T>
class C
{
public:
explicit C(const T& v = T()): value(v) {}
// when T is not a pointer type
T* operator->()
{
return &value;
}
private:
T value;
};
template <typename T>
class C<T*>
{
public:
explicit C(T* v = nullptr): value(v) {}
// when T is a pointer type
T* operator->()
{
return value;
}
private:
T* value;
};
または、C ++ 17互換のコンパイラを使用している場合は、if constexpr:を使用できます。
template <typename T>
class C
{
public:
explicit C(const T& v = T()): value(v) {}
// when T is not a pointer type
auto operator->()
{
if constexpr (std::is_pointer_v<T>)
return value;
else
return &value;
}
private:
T value;
};
それをテストするには:
int main()
{
struct Test
{
int x, y;
};
C<Test> c1({1, 2});
Test t = {3, 4};
C<Test*> c2(&t); // Initialize the pointer with some valid address, we are going to dereference it!
c1->x = 5;
c2->x = 5;
std::cout << c1->x << ' ' << c1->y << ' ' << t.x << ' ' << t.y << '\n';
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加