说我有这样的事情:
template<typename T, typename R>
struct MyStruct {
static R myfunc(T);
};
struct MyStructInst: S<int, double> {
static double myfunc(int i) { return i; }
};
然后,稍后,我有一个采用
M
的模板,我将假定该类型具有带有一个参数(例如myfunc
)的静态MyStructInst
函数。我想提取myfunc
的参数类型和结果类型:template<typename M,
typename ParamType = ???,
typename ResultType = decltype(declval(M::myfunc))> // I think this works?
struct MyStruct2 {
...
};
获得
ParamType
的最简单方法是什么? 最佳答案
关于什么
template <typename R, typename A0, typename ... As>
constexpr A0 firstArg (R(*)(A0, As...));
template <typename M,
typename PT = decltype(firstArg(&M::myfunc)),
typename RT = decltype(M::myfunc(std::declval<PT>()))>
struct MyStruct2
{ };
?
我的意思是...如果您声明(无需实现它,因为仅在
decltype()
中使用,因此仅返回类型很重要)接收函数类型的函数(我记得指向静态对象的指针方法就像指向传统函数的指针一样),该方法接收一个或多个参数并返回第一个参数的类型template <typename R, typename A0, typename ... As>
constexpr A0 firstArg (R(*)(A0, As...));
给定模板类型名称
M
,您可以使用以下方法获取myFunc()
方法的第一个参数(如果有):typename PT = decltype(firstArg(&M::myfunc))
给定
PT
(第一个类型参数的类型),您可以简单地模拟(在decltype()
中,使用std::declval()
)使用类型为myfunc()
的对象对PT
的调用来获得返回的类型。typename RT = decltype(M::myfunc(std::declval<PT>()))
以下是完整的编译示例
#include <string>
#include <type_traits>
template <typename T, typename R>
struct MyStruct
{ static R myfunc(T); };
struct MyStructInst
{ static double myfunc(int i) { return i; } };
template <typename R, typename A0, typename ... As>
constexpr A0 firstArg (R(*)(A0, As...));
template <typename M,
typename PT = decltype(firstArg(&M::myfunc)),
typename RT = decltype(M::myfunc(std::declval<PT>()))>
struct MyStruct2
{ using type1 = PT; using type2 = RT; };
int main ()
{
static_assert( std::is_same<int,
typename MyStruct2<MyStructInst>::type1>{}, "!");
static_assert( std::is_same<double,
typename MyStruct2<MyStructInst>::type2>{}, "!");
static_assert( std::is_same<long,
typename MyStruct2<MyStruct<long, std::string>>::type1>{}, "!");
static_assert( std::is_same<std::string,
typename MyStruct2<MyStruct<long, std::string>>::type2>{}, "!");
}