具有不同接口的策略类

编程入门 行业动态 更新时间:2024-10-25 22:29:16
本文介绍了具有不同接口的策略类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设有一个策略 FooPolicy 的算法。实现此策略的策略类具有静态成员函数 foo ,但是对于其中一些, foo code> int 参数,而对于其他人则不行。我试图通过 constexpr 静态数据成员使用具有不同接口的这些策略类的使用:

Suppose an algorithm that has a policy FooPolicy. Policy classes that implement this policy feature a static member function foo, but, for some of them, foo takes an int argument, while for others it does not. I am trying to enable the use of these policy classes with differing interfaces by means of constexpr static data members:

struct SimpleFoo { static constexpr bool paramFlag = false; static void foo() { std::cout << "In SimpleFoo" << std::endl; } }; struct ParamFoo { static constexpr bool paramFlag = true; static void foo(int param) { std::cout << "In ParamFoo " << param << std::endl; } }; template <typename FooPolicy> struct Alg { void foo() { if (FooPolicy::paramFlag) FooPolicy::foo(5); else FooPolicy::foo(); } }; int main() { Alg<ParamFoo> alg; alg.foo(); return 0; }

此代码不编译。 gcc 4.8.2 提供错误:

This code does not compile. gcc 4.8.2 gives the error:

ParamFoo :: foo()'

no matching function for call to ‘ParamFoo::foo()’

else FooPolicy :: foo();

else FooPolicy::foo();

else 子句被编译,尽管事实上在编译时已知 FooPolicy :: paramFlag true 。是否有办法让它工作?

The else clause gets compiled despite the fact that it is known at compile time that FooPolicy::paramFlag is true. Is there a way to make it work?

推荐答案

Is there a way to make it work?

一个解决方案是使用标记调度:

One solution is to use tag-dispatching:

#include <type_traits> template <typename FooPolicy> struct Alg { void foo() { foo(std::integral_constant<bool, FooPolicy::paramFlag>{}); } private: void foo(std::true_type) { FooPolicy::foo(5); } void foo(std::false_type) { FooPolicy::foo(); } };

DEMO

更多推荐

具有不同接口的策略类

本文发布于:2023-11-12 12:52:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   策略

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!