简体   繁体   中英

Get custom sizeof of std::function's variadic template argument types

I have a variadic template function that accepts std::function with variadic types. I want to find total sizeof of those types that std::function has, except that I want to treat double and float types as special, where sizeof(double) == 100 and sizeof(float) == 50 .

Here is pseudo-code (doesn't compile)

#include <iostream>
#include <functional>

// terminating case for T=double
template<>
size_t getSize<double>()
{
    return 100;
}

// terminating case for T=float
template<>
size_t getSize<float>()
{
    return 50;
}

// terminating case for T being anything else
template<class T>
size_t getSize<T>()
{
    return sizeof(T);
}

// recursive case
template<class T, class ...S>
size_t getSize<T, ...S>()
{
    return getSize<T>() + getSize<S>();
}

template <class ...T>
void print_function_arg_custom_size(std::function<void(T...)> f)
{
    size_t totalSize = 0;
    // get size recursively
    totalSize = getSize<T>(); 

    std::cout << "totalSize: " << totalSize << std::endl;
}

void foo(uint8_t a, uint16_t b, uint32_t c, double d)
{
    // noop
}

int main()
{
    std::function<void(uint8_t, uint16_t, uint32_t, double)> f = foo;
    print_function_arg_custom_size<uint8_t, uint16_t, uint32_t, double>(f);

    return 0;
}

One of the issues I'm having with this is that getSize doesn't like my template specialization.

Couple of errors :

template<class T>
size_t getSize<T>()
{
    return sizeof(T);
}

You don't need to provide a "specialization list" since it isn't a specialization. Also, since parameter packs can be empty, the compiler can't choose between the overloads getSize<T> and getSize<T, S...> . To fix it, make these changes:

template <typename T>
size_t getSize()
{
    return sizeof(T); 
}

// recursive case
template<class T, class U, class ...S>
size_t getSize()
{
    return getSize<T>() + getSize<U, S...>();
}

Live Demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM