【问题标题】:Get custom sizeof of std::function's variadic template argument types获取 std::function 的可变参数模板参数类型的自定义 sizeof
【发布时间】:2015-04-16 10:04:34
【问题描述】:

我有一个可变参数模板函数,它接受带有可变参数类型的 std::function。我想在std::function 拥有的那些类型中找到总共sizeof,除了我想将doublefloat 类型视为特殊类型,其中sizeof(double) == 100sizeof(float) == 50

这里是伪代码(不编译)

#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;
}

我遇到的一个问题是getSize 不喜欢我的模板专业化。

【问题讨论】:

    标签: c++ templates c++11 variadic-templates std-function


    【解决方案1】:

    几个错误:

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

    您不需要提供“专业化列表”,因为它不是专业化。此外,由于参数包可以为空,编译器无法在重载getSize&lt;T&gt;getSize&lt;T, S...&gt; 之间进行选择。要修复它,请进行以下更改:

    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.

    【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2022-01-23
    相关资源
    最近更新 更多