vendredi 16 novembre 2018

Try to make meta function which find method "size" in class

I am trying to write function getSize() which takes some template argument, tries to find method or field in this argument and return size() or size.

my code is:

#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <type_traits>


template <typename T>
class has_size {
private:
  typedef char Yes;
  typedef Yes No[2];

  template <typename U, U> struct really_has;

  template<typename C> static Yes& Test(really_has <size_t (C::*)() const,     &C::size>*);
  template<typename C> static Yes& Test(really_has <size_t (C::*)(), &C::size>*);

  template<typename> static No& Test(...);

public:
    static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
};

template <class T>
size_t get_size(T t){

    size_t res = 0;
    if(has_size<T>::value){

        res = t.size();
    }else{

        res = t.size;
    }


    return res;

}

int main() {
    std::vector<float> v(10);
    std::cout << std::boolalpha << has_size<std::vector<float>>::value <<     std::endl;
    std::cout << std::boolalpha << has_size<std::string>::value << std::endl;
    size_t res = get_size<v>;
    std::cout<< res;
    return 0;
}

The function has_size performs rightly in my example, but when I try to call getSize I got error:

prog.cpp: In function ‘int main()’:
prog.cpp:47:24: error: the value of ‘v’ is not usable in a constant expression
  size_t res = get_size<v>;
                    ^
prog.cpp:43:21: note: ‘v’ was not declared ‘constexpr’
  std::vector<float> v(10);
                 ^
prog.cpp:47:15: error: cannot resolve overloaded function ‘get_size’ based on conversion to type ‘size_t {aka long unsigned int}’
  size_t res = get_size<v>;
           ^~~~~~~~~~~

Aucun commentaire:

Enregistrer un commentaire