什么是用于第二括号<>中的以下函数模板的原因:

template<> void doh::operator()<>(int i)

此在 SO质疑其中有人建议,有括号operator()后失踪,但我找不到解释。

我理解的含义,如果它是具有以下形式的型专业化(全特):

template< typename A > struct AA {};
template<> struct AA<int> {};         // hope this is correct, specialize for int

然而,对于函数模板:

template< typename A > void f( A );
template< typename A > void f( A* ); // overload of the above for pointers
template<> void f<int>(int);         // full specialization for int

哪里这个配合到这个scenarion:

template<> void doh::operator()<>(bool b) {}

实施例的代码,似乎工作,不给任何警告/错误(用gcc 3.3.3):

#include <iostream>
using namespace std;

struct doh
{
    void operator()(bool b)
    {
        cout << "operator()(bool b)" << endl;
    }

    template< typename T > void operator()(T t)
    {
        cout << "template <typename T> void operator()(T t)" << endl;
    }
};
// note can't specialize inline, have to declare outside of the class body
template<> void doh::operator()(int i)
{
    cout << "template <> void operator()(int i)" << endl;
}
template<> void doh::operator()(bool b)
{
    cout << "template <> void operator()(bool b)" << endl;
}

int main()
{
    doh d;
    int i;
    bool b;
    d(b);
    d(i);
}

输出:

operator()(bool b)
template <> void operator()(int i)
有帮助吗?

解决方案

我看着它,并发现它是由14.5.2 / 2中指定:

  

一个局部类不得有构件的模板。访问控制规则(第11条)适用于成员模板的名称。析构函数不得成员模板。一个正常的(非模板)构件与给定的名称和类型和相同的名称的成员函数模板,该模板可以用于产生相同类型的特化,功能既可以在一个类中声明。当两个存在,使用该名称和类型的指非模板构件,除非显式模板参数列表被提供。

和它提供了一个示例:

template <class T> struct A {
    void f(int);
    template <class T2> void f(T2);
};

template <> void A<int>::f(int) { } // non-template member
template <> template <> void A<int>::f<>(int) { } // template member

int main()
{
    A<char> ac;
    ac.f(1); //non-template
    ac.f(’c’); //template
    ac.f<>(1); //template
}

请注意,在标准方面,specialization指的是你写的使用显式专业化的功能和使用实例化所产生的功能,在这种情况下,我们有一个专门产生做。 specialization并不仅仅指的是你创建使用明确专门的模板,但它通常仅用于哪些功能。

结论:GCC得到它错了。科莫,与我还测试了代码,得到它的权利,并发出一个诊断:

  

"ComeauTest.c" 16行:错误:"void doh::operator()(bool)"不是一个实体             可以明确的专业     template<> void doh::operator()(bool i)

请注意,它不是抱怨模板int(仅用于bool)的专门化,因为它不指代相同的名称类型:函数类型专业化将有是void(int),这是从功能型非模板的成员函数,它是void(bool)不同。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top