The property for checking the function accepts certain parameters, but does not return a type

I am trying to write a type trait in C ++ 11 (msvc2013) that will allow me to verify that a function type accepts certain parameters. I do not want him to check the return type. I think the idea is basically equivalent std::is_callable, but I am interested to know what is wrong with my approach, in addition to how to really solve the problem.

my implementation:

namespace traits
{
    namespace detail
    {
        template <typename T>
        struct is_write_function_impl
        {
            const char* c = nullptr;
            size_t l = 0;

            template<typename U>
            static auto test(U*)->decltype(declval<U>()(c, l), std::true_type);
            template<typename U>
            static auto test(...)->std::false_type;

            using type = decltype(test<T>(0));
        };
    }

    template <typename T>
    struct is_write_function : detail::is_write_function_impl<T>::type {};
}

my test case is:

std::ofstream os;
auto valid = std::bind(&std::ofstream::write, &os, 
    std::placeholders::_1, std::placeholders::_2);

// want this to be 'true' but get 'false'
std::cout << traits::is_write_function<decltype(valid)>::value;
+4
source share
1 answer

There are quite a few problems that will be detected by the best compiler;), but if you fix them, your code will work with VS 2013 (tested from 12.0.31101.00 Update 4):

static auto test(U*)->decltype(declval<U>()(c, l), std::true_type);
                               #1           #2     #3
  • std::declval.
  • static - static, . (std::declval<char const*>(), std::declval<std::size_t>()).
  • std::true_type - , decltype - . std::true_type{}.

.

+5

Source: https://habr.com/ru/post/1652063/


All Articles