有效的C ++:项目41-关于隐式接口的困惑

时间:2018-08-22 07:13:58

标签: c++ effective-c++

我正在阅读标题为“了解隐式接口和编译时多态性” 的有效C ++,第41项,它给出了本示例和下一个说明,但我不理解这一部分。

template<typename T>
void doProcessing(T& w)
{
     if (w.size() > 10 && w != someNastyWidget) {
     ...
  

...,T必须支持一个size成员函数,...,但是该成员函数不必返回整数类型。它甚至不需要返回数字类型。为此,它甚至不必返回为其定义了运算符>的类型!它需要做的就是返回一个x类型的对象,这样就可以调用一个>运算符{和{x1}}以及一个x类型的对象和一个int ...

能否请您解释一下它并给出更多示例?

1 个答案:

答案 0 :(得分:12)

这意味着// AMP change thrive-shortcode to landingpage link function add_shortcode_amp($content) { if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) { /// Define shortcode-name $mb_shortc = 'thrive_2step'; /// Define Mappings (thrive_2step id => Target URL for links in AMP) $ampMappings = array( "17503" => 'https://www.test.de/schreibtisch-workout-2', "17505" => 'https://www.test.de/merkmale-arbeitsplatz-kostenlos', "17506" => 'https://www.test.de/hoehenverstellbarer-schreibtisch-rentenverischerung-antrag'); /// Init Regex arrays $mb_rexp = array(); $subst = array(); foreach ($ampMappings as $key => $value) { $mb_rexp[] = '/\[('.$mb_shortc.').*?.id=[\'"]'.$key.'[\'"].*?\](.*?)\[\/\1\]?/'; $subst[] = '<a href="'.$value.'">${2}</a>'; } /// Process Content return preg_replace($mb_rexp, $subst, $content); } return $content; } add_filter( 'the_content', 'add_shortcode_amp', 6); function mbtest_hello_world() { return '<a>Hello World</a>'; } add_shortcode('AMPTEST', 'mbtest_hello_world'); function shortcode_switch4amp( $atts) { extract( shortcode_atts( array( 'regular' => 'regular', 'amp' => 'amp' ), $atts ) ); if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) { return do_shortcode(str_replace(array("{","}"), array("[","]"),$amp)); } else { return do_shortcode(str_replace(array("{","}"), array("[","]"), $regular)); } } add_shortcode('switch4amp', 'shortcode_switch4amp'); 函数可以返回可以比较(使用T::size()>值的任何值。


让我们看三个例子:

  1. 返回int

    int
  2. 返回一个可以转换为struct MyT { // Some stuff... int size() { return some_calculation_returning_int(); } // Some more stuff... }; 的对象:

    int
  3. 将可以与struct MySizeType { // Some stuff... operator int() { return some_calculation_returning_int(); } // Some more stuff... }; struct MyT { // Some stuff... MySizeType size() { return MySizeType(); } // Some more stuff... }; 比较的对象返回到>

    int

虽然很明显可以使用第一个变体,但也可以使用另外两个 。这是因为它们以某种方式返回可以与struct MyOtherSizeType { // Some stuff... operator>(int other) { return some_calculation_returning_int() > other; } // Some more stuff... }; struct MyT { // Some stuff... MyOtherSizeType size() { return MyOtherSizeType(); } // Some more stuff... }; 值进行比较的内容。

如果我们“扩展”三个变体:

  1. int就是这样。

  2. w.size() > 10将是w.size() > 10。这里的w.size().operator int() > 10转换函数将用于将MySizeType::operator int()对象转换为可以比较的MySizeType值。

  3. int将是w.size() > 10。这里的w.size().operator>(10)函数将用于比较本身。

参考

  1. operator overloading
  2. user-defined conversion