gpt4 book ai didi

c++ - 递归 Variadic 模板函数的编译错误

转载 作者:可可西里 更新时间:2023-11-01 17:29:46 25 4
gpt4 key购买 nike

我已经在 Code::Blocks 中准备了一个简单的可变参数模板测试,但是我收到了一个错误:

No matching function for call to 'OutputSizes()'

这是我的源代码:

#include <iostream>
#include <typeinfo>

using namespace std;

template <typename FirstDatatype, typename... DatatypeList>
void OutputSizes()
{
std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl;
OutputSizes<DatatypeList...>();
}

int main()
{
OutputSizes<char, int, long int>();
return 0;
}

我正在使用 GNU GCC 和 -std=C++0x。使用 -std=gnu++0x 没有任何区别。

最佳答案

这是消除基本情况歧义的方法:

#include <iostream>
#include <typeinfo>

template <typename FirstDatatype>
void OutputSizes()
{
std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl;
}

template <typename FirstDatatype, typename SecondDatatype, typename... DatatypeList>
void OutputSizes()
{
OutputSizes<FirstDatatype>()
OutputSizes<SecondDatatype, DatatypeList...>();
}

int main()
{
OutputSizes<char, int, long int>();
}

关于c++ - 递归 Variadic 模板函数的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5035889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com