Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将运行时调用引入编译时模板计算_C++_Templates_C++11_Variadic Templates - Fatal编程技术网

C++ 将运行时调用引入编译时模板计算

C++ 将运行时调用引入编译时模板计算,c++,templates,c++11,variadic-templates,C++,Templates,C++11,Variadic Templates,假设我有一个在编译时计算sizeof事物的结构 template<typename T> struct GetTypeSize { enum { value = sizeof(T) }; }; // treat float as special template<> struct GetTypeSize<float> { enum { value = SIZEOF_FLOAT }; }; template<typename...&g

假设我有一个在编译时计算
sizeof
事物的结构

template<typename T>
struct GetTypeSize
{
    enum { value = sizeof(T) };
};

// treat float as special
template<>
struct GetTypeSize<float>
{
    enum { value = SIZEOF_FLOAT };
};


template<typename...>
struct GetSize
{
    enum { value = 0 };
};

template<typename Head, typename... Tail>
struct GetSize<Head, Tail...>
{
    enum { value = GetTypeSize<Head>::value + GetSize<Tail...>::value };
};

因此,我想知道在单个构造中这样混合编译时和运行时是否可行,以及如何将其存档。

您是否可以使用c++14?实际上,简单读取
{return sizeof(T)}
的函数调用将内联,所以这真的不重要。您可以添加
constexpr
来进一步鼓励这种做法。@DavidW是的,但您可以使用C++141在
constexpr
函数中评估
std::vector::size()*sizeof(T)
)我只是想指出,对于性能,您可能不需要这样做。2) 在
constexpr
中使用
std::vector::size()
是否依赖于能够在编译时计算向量长度,这通常是不正确的?@DavidW建议这一点的原因是,使用C++14
constexpr
可以是编译时或运行时,而不仅仅是运行时(常规函数)或仅编译时(模板元函数)。这正是OP想要的。
template <class ...T>
void foo(T... arg)
{
    const size_t size = GetSize<T...>::value;
    std::cout << "size of the thing is: " << size << std::endl;

    // do stuff with arg
}
const size_t size = 4 + 8 + 2 + (argN.size() * 4) + 2;