c – 模板模板函数参数

前端之家收集整理的这篇文章主要介绍了c – 模板模板函数参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How to pass a template function in a template argument list2个
对于我的生活,我无法让这个简单的奥术模板魔法工作:
  1. template<typename T,int a,int b>
  2. int f(T v){
  3. return v*a-b; // just do something for example
  4. }
  5.  
  6. template<typename T,int b,template<typename,int,int> class func>
  7. class C{
  8. int f(){
  9. return func<T,a,b>(3);
  10. }
  11. };
  12.  
  13. int main(){
  14. C<float,3,2,f> c;
  15. }

这可能不涉及仿函数吗?

解决方法

f应该是一个类 – 你有一个功能.

见下文:

  1. // Class acts like a function - also known as functor.
  2. template<typename T,int b>
  3. class f
  4. {
  5. int operator()(T v)
  6. {
  7. return v*a-b; // just do something for example
  8. }
  9. };
  10.  
  11. template<typename T,int> class func>
  12. class C
  13. {
  14. int f()
  15. {
  16. return func<T,b>(3);
  17. }
  18. };
  19.  
  20. int main()
  21. {
  22. C<float,f> c;
  23. }

…如果需要移植遗留代码,请使用改编版本(将函数调整为类模板):

  1. #include <iostream>
  2.  
  3.  
  4. template<typename T,int b>
  5. int f(T v)
  6. {
  7. std::cout << "Called" << std::endl;
  8. return v*a-b; // just do something for example
  9. }
  10.  
  11. template<typename T,int> class func>
  12. struct C
  13. {
  14. int f()
  15. {
  16. return func<T,b>(3);
  17. }
  18. };
  19.  
  20. template <class T,int b>
  21. struct FuncAdapt
  22. {
  23. T x_;
  24. template <class U>
  25. FuncAdapt( U x )
  26. : x_( x )
  27. {}
  28. operator int() const
  29. {
  30. return f<T,b>( x_ );
  31. }
  32. };
  33.  
  34. int main()
  35. {
  36. C<float,FuncAdapt > c;
  37. c.f();
  38. }

猜你在找的C&C++相关文章