简单的模板推导错误
simple template deduction error
我正在尝试使用一些模板自动生成const
成员函数对。请帮我编译这个代码。
template<typename T>
struct Constifier
{
typedef T Type;
};
template<typename T>
struct Constifier<T &>
{
typedef const T &Type;
};
template<typename T>
struct Constifier<T &&>
{
typedef const T &&Type;
};
template<typename T>
struct Constifier<T *>
{
typedef const T *Type;
};
template<typename F>
struct ReturnType;
template<typename R, typename ...Ts>
struct ReturnType<R (*)(Ts ...ts)>
{
typedef R Type;
};
template<typename R, typename T, typename ...Ts>
struct ReturnType<R (T::*)(Ts ...ts)>
{
typedef R Type;
};
template<typename T, typename F, typename ...Ts>
auto callConstVersion(const T *t, F f, Ts ...ts)
{
return const_cast<typename Constifier<typename ReturnType<F>::Type>::Type>((const_cast<T *>(t)->*f)(ts...));
}
struct A
{
A *p;
A *get() {return p;}
const A *get() const {return callConstVersion(this, &A::get);}
};
get
成员函数重载,因此,给定&A::get
作为参数,F
变得不可推导。要消除两者之间的歧义,请使用static_cast
:
static_cast<const A*(A::*)() const>(&A::get) // for the const overload
static_cast<A*(A::*)()>(&A::get) // for the non-const overload
或在模板参数列表中显式指定F
:
callConstVersion<A,A*(A::*)()>(this, &A::get);
或者,如果你知道callConstVersion
应该总是采用一个非常常量的非易失性非ref限定成员函数,你可以如下重新定义它:
template<typename T, typename R, typename... Args, typename ...Ts>
auto callConstVersion(const T *t, R(T::*f)(Args...), Ts ...ts)
(那么普通callConstVersion(this, &A::get)
应该可以工作(。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 显示错误输出的简单数组排序程序
- 无法找到简单的开关大小写枚举错误
- 处理简单 cpp 类构造函数中的错误
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- 一个非常简单的win32套接字代码,但工作错误
- OpenGL C++(制作简单窗口时抛出错误)
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- boost::spirit--试图编译大多数简单代码的编译器错误
- Cmake无法在qt-creater/collect2上编译简单的测试程序:错误:ld
- 奇怪的 G++ 错误,带有关于左值和赋值的简单代码
- 编译简单的多文件类程序时出现未定义的引用错误
- 来自简单循环的 OpenAcc 错误:内核执行期间的非法地址
- 使用提升过程编译简单的应用程序会生成错误
- 简单的字符串替换给出错误,尽管参数正确
- 为什么使用 int64_t 会产生错误的结果,而双精度则按预期进行简单的整数乘法
- C++中一个非常简单的枚举类错误
- 为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
- 用于二分搜索的错误简单功能(C++)
- 指针错误导致的分段错误(简单..)