C ++“如果是,则为其他"模板替换 [英] C++ "if then else" template substitution

查看:47
本文介绍了C ++“如果是,则为其他"模板替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个模板,如下所示:

I would like to declare a template as follows:

template <typename T>
{ 
  if objects of class T have method foo(), then 
   const int k=1
  else 
   if class has a static const int L then
    const int k=L
   else 
    const int k=0;


}

我该怎么做?总的来说,我想要一种用于设置静态const的机制 基于T的属性(或T内定义的typedef).

How can I do this? In general, I would like a mechanism for setting static consts based on properties of T (or typedef defined inside T).

推荐答案

外部部分当然很简单.使用boost :: mpl :: if_决定从元函数返回哪种int_类型,然后访问其中的值.没关系.

The outer part is of course quite easy. Use boost::mpl::if_ to decide which int_ type to return from your metafunction and then access the value in it. No big deal.

您试图找出类型X是否具有函数f()的部分仍然很简单,但是不幸的是您找不到通用的答案.每次您需要这种检查时,都必须编写一个自定义的元函数才能将其找出来.使用SFINAE:

The part where you try to find out if type X has a function f() is still fairly straight forward but unfortunately you'll not find a generic answer. Every time you need this kind of inspection you'll have to write a custom metafunction to find it out. Use SFINAE:

  template < typename T >
  struct has_foo
  {
    typedef char (&no)  [1];
    typedef char (&yes) [2];

    template < void (T::*)() >
    struct dummy {};

    template < typename S >
    static yes check( dummy<&S::foo> *);

    template < typename S >
    static no check( ... );

    enum { value = sizeof(check<T>(0)) == sizeof(yes)  };
  };

哦,用BOOST_MPL_HAS_XXX()为您的静态常量L创建一个检查器

Oh, and create a checker for your static const L with BOOST_MPL_HAS_XXX()

这篇关于C ++“如果是,则为其他"模板替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆