2
4

2 回答 2

3

You could use a simple pair of overloaded function templates:

template<typename T>
T& access(T& t) { return t; }

template<typename T>
T& access(T* t) { return *t; }

And then use them this way:

access(val).member = 42;

For instance:

template<typename T>
struct A
{
    void do_it(T& val)
    {
        access(val).member = 42;
    }
};

struct Type
{
    int member = 0;
};

#include <iostream>

int main()
{
    A<Type> a;
    Type t;
    a.do_it(t);
    std::cout << t.member << std::endl;

    A<Type*> a2;
    Type* t2 = new Type(); // OK, I don't like this, but just to show
                           // it does what you want it to do...
    a2.do_it(t2);
    std::cout << t2->member;

    delete t2;             // ...but then, don't forget to clean up!
}

Here is a live example.

于 2013-03-20T16:48:58.843 回答
2

The best idea is probably to specialize your class for pointer types.

template<class T>
class A{ ...}; 

template<>
class A<T*> { //implement for pointers
};

If you feel that this is too verbose, you can use overload a get_ref function:

template<class T> T& get_ref(T & r) {return r;}
template<class T> T& get_ref(T* r) {return *r;}

template<class T>
class A {
   void do(T val) {
     get_ref(val).member ...
  }
}
于 2013-03-20T16:54:06.343 回答