简体   繁体   English

C++ 函数模板全特化错误

[英]C++ function template full specialization error

I am having this template matching error.我有这个模板匹配错误。 I know partial specialization is not allowed in for function template, but I think it should work with full specialization.我知道函数模板中不允许部分专业化,但我认为它应该与完全专业化一起使用。 What change do I need to make to fix this issue ?我需要做哪些改变来解决这个问题? Thanks.谢谢。

#include <iostream>

template<typename T>
void allocate(){
    std::cout << "default" << std::endl;
}

template<>
void allocate<int>() {
    std::cout << "int" << std::endl;
}

template<>
void allocate<double>() {
    std::cout << "double" << std::endl;    
}




int main()
{
    allocate();  // Compiler error, I expect this should match the first template function.
    allocate<int>();
    allocate<double>();
    
    return 0;
}

You need to specify the template argument explicitly, the template parameter T can't be deduced from the context.您需要明确指定模板参数,模板参数T不能从上下文中推导出来。 eg例如

allocate<void>();

Or specify default argument for the template parameter, eg或者为模板参数指定默认参数,例如

template<typename T = void>
void allocate(){
    std::cout << "default" << std::endl;
}

then you can call it as那么你可以称之为

allocate(); // T is void

The primary template needs the template parameter to be specified explicitly, so you can do:主模板需要显式指定模板参数,因此您可以执行以下操作:

allocate<struct T>();  // ok

and since T is a new type named only for the purpose of this call, there is guaranteed to not be a specialization for this type, and the primary template will be called.并且由于T是一个新类型,仅为了此调用的目的而命名,因此保证不会对此类型进行特化,并且将调用主模板。


You could also give a default type for the template parameter in the primary:您还可以为主要中的模板参数提供默认类型:

template<typename T = struct Default>
void allocate(){
    std::cout << "default" << std::endl;
}

and again, no specialization can exist for Default since this type only exists in the scope of the primary template.同样, Default不存在特化,因为这种类型只存在于主模板的范围内。

Now you can call the primary template without template parameters:现在您可以在没有模板参数的情况下调用主模板:

allocate();

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

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