26 Ocak 2017 Perşembe

std::result_of

Giriş
Belirtilen metodun sonuç tipine erişmemizi sağlar.

Nesne Fully Defined Olmalıdır
Metod bir nesne içinde ise nesnenin tanımlanmasının bitmiş olması gerekir. Şu kod derlenmez.
struct Foo
{
  static auto foo(int bar)
  {
    return 0;
  }

  typedef std::result_of<decltype(Foo::foo)> foo_t;
};
Çıktı olarak şunu alırız.
"function 'foo' with deduced return type cannot be used before it is defined"
Sebebi ise kodun aslında şuna benzemesi. Foo header'ı parse edilirken önce declaration bulunur. Dolayısıyla foo metonun ne döndüğünü derleyici bilemez.
struct Foo
{
  static auto foo(int bar);

  typedef std::result_of<decltype(Foo::foo)> foo_t;
};

auto Foo::foo(int bar)
{
  return 0;
}

Örnek 1
Şöyle yaparız.
#include<type_traits>
#include<iostream>
using namespace std;


template <class F, class R = typename result_of<F()>::type>
R call(F& f) { return f(); }

struct S {
    double operator()(){return 0.0;}
};

int main()
{
  S obj;
  call(obj);//ok

  return 0;
}
Örnek 2
auto metodlar ile de kullanılabilir. Şöyle yaparız
auto foo(int bar)
{
  return 0;
}

typedef std::result_of<decltype(foo)> foo_t;
Şöyle yaparız.
struct Foo
{
  static auto foo(int bar)
  {
    return 0;
  }
};

typedef std::result_of<decltype(Foo::foo)> foo_t;



Hiç yorum yok:

Yorum Gönder