C++11 - std::d eclval<T>() 方法名称
C++11 - std::declval<T>() name of method
是否有一种方法,如何在std::declval<T>()
之后传递方法名称作为模板参数?
到目前为止,我有这个:
template<typename T, typename ... Args>
struct MethodInfo
{
using type = decltype(std::declval<T>().foo(std::declval<Args>() ...)) (T::*)(Args ...);
};
但我想" foo
"是模板参数。
这不是你要求的,但我认为这可能符合你的需要:
#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, "");
}
演示因为,函数名是一个非类型模板参数,我认为这是目前为止唯一的解决方案。
在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, "");
演示但是对于c++ 17中的auto
模板参数,您可以这样做:
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, "");
演示相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法