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

标签 c++ templates

我有这个最小的、人为设计的 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/

相关文章:

C++ 应用程序找不到 com dll,因为编译器生成的 .tlh 文件具有不正确的 guid

c++ - 用于面部和眼睛检测的最佳 opencv 版本

c++ - 为什么 std 智能指针类型析构函数不继承指向对象的 noexcept dtor 状态

c++ - 减少STL vector 的容量

c++ - 如何在 Visual Studio 2019 预览版中启用 C++ 模块支持

c++ - std::vector 作为模板函数参数

c++ - 尽管已声明,但找不到模板化函数

java - 通过java API进行elasticsearch的纯字符串模板查询?

c++ - 创建模板化结构的 std::list (C++)

c++ - 模板非类型模板参数?