Type definition from a non-piggy type template parameter

I would like to do this:

template <typename T x>
struct Test {
    T val{x};
};

int main() {
    Test<3> test;
    return test.val;
}

But I can not. Correctly?


I answered the question here and I use the following pattern:

template <typename T, typename V, typename VP, V(T::*getf)(), void (T::*setf)(VP)>

Each type is specified manually. But this is duplication, because T, Vand are VPalready contained in pointers to member functions getfand setf.


But if I try the template only with

template <V(T::*getf)(), void (T::*setf)(VP)>

or

template <V(T::*getf)(), void (T::*setf)(VP), typename T, typename V, typename VP>

then types cannot be defined.


Next, I tried specialization:

template <typename T, typename T2>
struct Accessor;

template <typename V, typename T, typename VP>
struct Accessor <V(T::*)(), void (T::*)(VP)>

which will determine all types if used

typedef Accessor<
    decltype(&TargetClass::GetFoo), 
    decltype(&TargetClass::SetFoo)> fooAcessor;

But now I have no more pointers, only types.


Is there a way to write a template so that types can be determined automatically from a non-piggy type template parameter?

+4
1

, ?

++ 17, , auto:

template <auto x>
struct Test {
    decltype(x) val{x};
};

++ 17, no. :

template <class T, T x>
struct Test {
    T val{x};
};
+12

Source: https://habr.com/ru/post/1666544/


All Articles