在模板类中:使用类方法作为另一类方法的模板参数
Within a template class: Use a class method as a template argument for another class method
考虑以下代码:
template < class A >
class XX {
public:
template <int (*CC)() >
int bla (){ return CC(); }
int stam() {return 0;}
int f() {
return bla<stam>();
}
};
int main()
{
XX<int> xx;
printf(" this is %dn", xx.f());
return 0;
}
它在
上失败test.cpp: In member function ‘int XX<A>::f() [with A = int]’:
test.cpp:14: instantiated from here
test.cpp:8: error: ‘int XX<A>::stam() [with A = int]’ cannot appear in a constant-expression**
考虑到这一点很明显。在实例化模板之前,stam
不存在,因此它没有函数地址。当实例化模板时,该实例在代码中的某个地方进行了未充实,然后stam
获取一个地址。因此,该地址在编译时并不恒定(尽管有些工作可能是 - 但这是不支持的)。
所以为什么我要这样做。我可以使用功能指针或虚拟功能。实际上,使用stam
的bla
(有stam1
和stam2
)称其为亿万次,甚至是较小的性能改进(例如不使用间接)。
当然有解决方案:创建几乎相同的bla1
和bla2
。写一个预处理器宏。我想知道是否有优雅的解决方案。
这会编译OK:
#include <cstdio>
using namespace std;
template < class A >
class XX {
public:
template <int (XX<A>::*CC)()>
int bla (){ return (this->*CC)(); }
int stam() {return 0;}
int f() {
return bla<&XX<A>::stam>();
}
};
int main()
{.
XX<int> xx;
printf(" this is %dn", xx.f());
return 0;
}
修复程序是为指针到方法模板参数和正确的语法使用正确的签名来指定方法指针。(实际上,您可以在那里省略<A>
。)
问题是stam()是成员函数,而不是免费函数,因此需要用"此"指针调用。
阅读有关成员功能指针的本教程:
http://www.parashift.com/c -faq/pointers-to-members.html
相关文章:
- 如何制作一个将函数作为参数的类方法
- 使用用户定义的参数调用future/async并调用类方法
- 如何在Visual Studio 2017上将类方法设置为参数并将它们与lambda一起使用?
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 是否可以基于类模板的参数调用类方法和全局方法
- 将方法参数类型更改为子类中的派生类
- C++ 模板:重载时找不到基类类型参数方法
- 如何在 C 中包装C++具有参数的类方法或返回另一个C++类的实例?
- 将 std::ofstream 对象作为参数传递给类方法
- 将指针类方法作为参数传递给其他类方法C
- 如何调用作为参数给出的C++类方法?
- 如何将基类方法超载作为参数传递到C 中的模板类
- C++11可变参数模板方法完全影子基类方法
- 我如何根据某些模板参数影响模板类方法的返回类型
- 在声明C 期间具有值的类方法的初始化参数
- r-使用Rcpp模块公开带有引用参数的c++类方法时出错
- 如何在子类方法中更改参数
- 接受 lambda 作为参数的类方法 - 错误消息
- 类方法接受表示各种参数数函数的 lambda
- 如何在.dll类方法参数中传递对象