简体   繁体   English

为什么需要在此C ++模板中指定类型?

[英]Why is it necessary to specify the type in this C++ template?

I have this minimal, contrived example of C++ code, with a template struct with a default type parameter: 我有这个最小的,人为的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;
}

When I try to compile this code, I get the following error with g++ 4.9.1: 当我尝试编译此代码时,我得到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;
                  ^

If I specify int for T, then it compiles and produces the expected output (43.24). 如果我为T指定int,那么它编译并产生预期的输出(43.24)。 My question is, why is this necessary to do? 我的问题是,为什么这有必要呢? What does the default type parameter do in the definition of AddsFourtyTwo, if you need to specify the type anyway? 如果您需要指定类型,默认类型参数在AddsFourtyTwo的定义中会做什么?

您不需要指定类型,但语言不允许使用模板作为实际类型而不指定某个参数列表:

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

Using the template class requires the following syntax: 使用模板类需要以下语法:

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

will compile and use the default parameter. 将编译并使用默认参数。 That's confusing since the same is not required for templated methods. 这是令人困惑的,因为模板化方法不需要相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM