我有一个类似于以下的类,并希望通过类模板T对'->'运算符进行特殊化。特殊化应取决于类型T是否为指针类型。我已经搜索了解决方案,但没有找到针对此特定问题的任何解决方案。
mockProps
感谢您的帮助!
答案 0 :(得分:1)
您需要partial specialization 另外,在引用指针时也需要小心。您原来的示例很可能会崩溃。
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';
}