相关疑难解决方法(0)

SFINAE + sizeof =检测表达式是否编译

我刚刚发现了如何检查是否operator<<提供了类型.

template<class T> T& lvalue_of_type();
template<class T> T  rvalue_of_type();

template<class T>
struct is_printable
{
    template<class U> static char test(char(*)[sizeof(
        lvalue_of_type<std::ostream>() << rvalue_of_type<U>()
    )]);
    template<class U> static long test(...);

    enum { value = 1 == sizeof test<T>(0) };
    typedef boost::integral_constant<bool, value> type;
};
Run Code Online (Sandbox Code Playgroud)

这个技巧是众所周知的,还是我刚刚获得了诺贝尔奖的元编程?;)

编辑:我使代码更容易理解,更容易适应两个全局函数模板声明lvalue_of_typervalue_of_type.

c++ metaprogramming sfinae

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

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

我的应用程序中有一个问题,我想声明函数应用程序将被编译器拒绝.有没有办法用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
查看次数

标签 统计

c++ ×2

sfinae ×2

c++-concepts ×1

metaprogramming ×1

type-traits ×1