有没有办法,如何在std::declval<T>()之后传递一个方法名作为模板参数
到目前为止,我有这样的想法:
template<typename T, typename ... Args>
struct MethodInfo
{
using type = decltype(std::declval<T>().foo(std::declval<Args>() ...)) (T::*)(Args ...);
};但是我希望"foo“成为模板参数。
发布于 2016-11-05 04:33:32
这并不完全符合你的要求,但我认为这可能有点适合你的需要:
#include <type_traits>
#include <tuple>
#include <iostream>
template<typename T, typename... Args>
struct MethodInfo {
template<typename Ret>
static auto get(Ret(T::*)(Args...)) -> Ret(T::*)(Args...);
};
struct Foo {
int foo(int);
int foo(int, int);
};
int main() {
static_assert(std::is_same<
int(Foo::*)(int),
decltype(MethodInfo<Foo, int>::get(&Foo::foo))
>::value, "");
}演示
因为,函数名是一个非类型的模板参数,我认为到目前为止,这是唯一的解决方案。
发布于 2016-11-04 08:56:21
在C++11中,您可以这样做,但它很大程度上违背了该类的目的:
template<typename T, typename U, U ptr, typename... Args>
struct TypeOverload;
template<typename T, typename U, typename... Args, U(T::* ptr)(Args...)>
struct TypeOverload<T, U(T::*)(Args...), ptr, Args...>
{
using type = decltype((std::declval<T>().*ptr)(std::declval<Args>() ...)) (T::*)(Args ...);
};因为它的用法如下:
using bar_t = TypeOverload<Foo, decltype(&Foo::bar), &Foo::bar, int, int>::type;
static_assert(std::is_same<bar_t, void(Foo::*)(int,int)>::value, "");演示
但是,使用auto模板参数在C++17中,您可以拥有以下内容:
template<typename T, auto ptr, typename... Args>
struct TypeOverload
{
using type = decltype((std::declval<T>().*ptr)(std::declval<Args>() ...)) (T::*)(Args ...);
};你可以这样使用它:
using bar_t = TypeOverload<Foo, &Foo::bar, int, int>::type;
static_assert(std::is_same<bar_t, void(Foo::*)(int,int)>::value, "");演示
https://stackoverflow.com/questions/40418367
复制相似问题