相关疑难解决方法(0)

如何检查operator ==是否存在?

我试图创建一个示例,它将检查operator==(成员或非成员函数)的存在.检查一个类是否有成员operator==很容易,但如何检查它是否有非成员operator==

这就是我所要做的:

#include <iostream>

struct A
{
    int  a;

    #if 0
    bool operator==( const A& rhs ) const
    {
        return ( a==rhs.a);
    }
    #endif
};
#if 1
bool operator==( const A &l,const A &r )
{
    return ( l.a==r.a);
}
#endif


template < typename T >
struct opEqualExists
{
    struct yes{ char a[1]; };
    struct no { char a[2]; };

    template <typename C> static yes test( typeof(&C::operator==) );
    //template <typename C> static yes test( …
Run Code Online (Sandbox Code Playgroud)

c++ sfinae

50
推荐指数
5
解决办法
1万
查看次数

如何在编译时检查表达式是非法的?

我的应用程序中有一个问题,我想声明函数应用程序将被编译器拒绝.有没有办法用SFINAE来检查?

例如,假设我想验证std::transformconst范围是违法的.这是我到目前为止所拥有的:

#include <algorithm>
#include <functional>
#include <iostream>

namespace ns
{

using std::transform;

template<typename Iterator1, typename Iterator2, typename UnaryFunction>
  struct valid_transform
{
  static Iterator1 first1, last1;
  static Iterator2 first2;
  static UnaryFunction f;

  typedef Iterator2                   yes_type;
  typedef struct {yes_type array[2];} no_type;

  static no_type transform(...);

  static bool const value = sizeof(transform(first1, last1, first2, f)) == sizeof(yes_type);
};

}

int main()
{
  typedef int *iter1;
  typedef const int *iter2;
  typedef std::negate<int> func;

  std::cout << "valid transform compiles: " << …
Run Code Online (Sandbox Code Playgroud)

c++ sfinae type-traits c++-concepts

12
推荐指数
1
解决办法
1290
查看次数

使用SFINAE检查全局运算符<<?

我想有几个重载的全局to_string()函数,它们采用某种类型T并将其转换为字符串表示形式.对于一般情况,我希望能够写:

template<typename T,class OutputStringType> inline
typename enable_if<!std::is_pointer<T>::value
                && has_insertion_operator<T>::value,
                   void>::type
to_string( T const &t, OutputStringType *out ) {
  std::ostringstream o;
  o << t;
  *out = o.str();
}
Run Code Online (Sandbox Code Playgroud)

has_insertion_operator到目前为止,我的实施是:

struct sfinae_base {
  typedef char yes[1];
  typedef char no[2];
};

template<typename T>
struct has_insertion_operator : sfinae_base {
  template<typename U> static yes& test( U& );
  template<typename U> static no& test(...);

  static std::ostream &s;
  static T const &t;

  static bool const value = sizeof( test( s << t ) …
Run Code Online (Sandbox Code Playgroud)

c++ templates sfinae

11
推荐指数
1
解决办法
2900
查看次数

标签 统计

c++ ×3

sfinae ×3

c++-concepts ×1

templates ×1

type-traits ×1