user667967
user667967

Reputation: 648

Simplification of Template Class Specification

I am very interested in the possibilities of template classes. Now, I am wondering how I can achieve following:

    Const<5>::getValue();

At the moment I can do this:

    Const<int, 5>::getValue());

And that's the implementation of the class:

    template <typename T, T value>
    class Const {
    public:
        typedef T Type;

        static T getValue() {
            return value;
        }
    };

I know this is just a very silly example, but once I can do that I could simplify following line:

    Getter<int, TestClass, &TestClass::get> getter;

to just:

    Getter<&TestClass::get> getter;

That would be TestClass :

    class TestClass {
    private:
        int _value;
    public:
        int get() {
            return _value;
        }
    };

Thanks for your help!

[EDIT-1]

In regards to J.N. yes, C++11 would be fine.

In regards to Xeo, I tried to use #define AUTO_ARG(x) decltype(x), x but that doesn't work within TestClass.

[EDIT-2]

In regards to KennyTM, when I declare the Getter<...> g within TestClass it doesn’t work with Getter<AUTO_ARG(&TestClass::get)> it only works with Getter<int (TestClass::*)() const, &TestClass::get>.

Now I am wondering if this is just a bug in Visual Studio???

Upvotes: 1

Views: 313

Answers (1)

kennytm
kennytm

Reputation: 523344

You could still use AUTO_ARG(x) as given by @Xeo's link. If you need to get the return type or the class type, just use pattern matching (i.e. template specialization):

template <typename T, T mem_fun_ptr>
struct Getter;

template <typename R, typename C, typename... A, R (C::*mem_fun_ptr)(A...) const>
struct Getter<R (C::*)(A...) const, mem_fun_ptr>
{
    typedef R return_type;
    typedef C class_type;
};

#define AUTO_ARG(x) decltype(x),(x)

class TestClass {
private:
    int _value;
public:
    int get() const {
        return _value;
    }
};

Getter<AUTO_ARG(&TestClass::get)> g;

Upvotes: 2

Related Questions