gpt4 book ai didi

c++ - 为什么需要在这个 C++ 模板中指定类型?

转载 作者:太空狗 更新时间:2023-10-29 20:03:45 25 4
gpt4 key购买 nike

我有这个最小的、人为设计的 C++ 代码示例,带有一个带有默认类型参数的模板结构:

#include <iostream>
using namespace std;

template <class T=int>
struct AddsFourtyTwo {
template <class U>
static U do_it(U u) {
return u + static_cast<T>(42);
}
};

int main() {
double d = 1.24;
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
}

当我尝试编译此代码时,在 g++ 4.9.1 中出现以下错误:

$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:14:18: error: 'template<class T> struct AddsFourtyTwo' used without template parameters
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
^

如果我为 T 指定 int,那么它会编译并产生预期的输出 (43.24)。我的问题是,为什么有必要这样做?如果无论如何都需要指定类型,默认类型参数在 AddsFourtyTwo 的定义中有什么作用?

最佳答案

您不需要指定类型,但该语言不允许在不指定一些参数列表的情况下将模板用作实际类型:

std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;

关于c++ - 为什么需要在这个 C++ 模板中指定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329848/

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