问题
I wish I could do this:
template <typename T x>
struct Test {
T val{x};
};
int main() {
Test<3> test;
return test.val;
}
But I can't. Right?
I was answering a question here and I use the following template:
template <typename T, typename V, typename VP, V(T::*getf)(), void (T::*setf)(VP)>
Each of the types are manually specified. But that is a duplication because T
, V
and VP
are already contained in the pointers to member functions getf
and setf
's types.
But if I try a template with only
template <V(T::*getf)(), void (T::*setf)(VP)>
or
template <V(T::*getf)(), void (T::*setf)(VP), typename T, typename V, typename VP>
then the types cannot be determined.
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 of the types if use
typedef Accessor<
decltype(&TargetClass::GetFoo),
decltype(&TargetClass::SetFoo)> fooAcessor;
But now I don't have the pointers anymore, only the types.
Is there a way to write a template so that the types can be determined automatically from the non-type template parameter?
回答1:
Is there a way to write a template so that the types can be determined automatically from the non-type template parameter?
In C++17, yes, thanks to declaring non-type template parameters with auto:
template <auto x>
struct Test {
decltype(x) val{x};
};
Before C++17, no. You'd have to write:
template <class T, T x>
struct Test {
T val{x};
};
来源:https://stackoverflow.com/questions/41599226/determine-type-from-non-type-template-parameter