为什么将'<'作为'operator <'而不是标记来包含模板参数?

Yan*_*Xie 2 c++ templates

我的C++代码如下:

//test.cpp
#include <iostream>
using namespace std;

template <int SIZE, class T>
struct A
{
    void g(int x, const T& t)
    {
        t.f<SIZE>(x);
    }
};

struct B
{
    template <int SIZE>
    void f(int x) const
    {
        cout << SIZE << ": " << x << endl;
    }
};


int main(void)
{
    A<3, B> a;
    B b;
    a.g(9, b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

用g ++编译它时出现了一个令人惊讶的错误(版本是4.8.2):

test.cpp: In instantiation of ‘void A<SIZE, T>::g(int, const T&) [with int SIZE = 3; T = B]’:
test.cpp:27:13:   required from here
test.cpp:9:12: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
         t.f<SIZE>(x);
            ^
Run Code Online (Sandbox Code Playgroud)

为什么采取<作为operator<,而不是一个标志围住模板参数?

Kon*_*lph 7

因为代码本质上是模糊的1所以编译器必须决定哪种方式.并且C++标准委员会任意决定,如果有疑问,假设名称是变量,而不是类型.

如果您希望将代码解析为模板,则需要明确说明:

t.template f<SIZE>(x);
Run Code Online (Sandbox Code Playgroud)

1在解析此代码时,t由于它是模板,因此尚未知道其类型.请考虑以下类型:

struct T {
    int f;
};
Run Code Online (Sandbox Code Playgroud)

如果您现在A使用该类型进行实例化,则会获得(自模板实例化以来的伪代码):

void A<3, T>::g(int x, T const& t) {
    ((t.f) < 3) > x;
}
Run Code Online (Sandbox Code Playgroud)

我添加了括号以便澄清:这是编译器看到你的代码的方式,它完全有效(尽管是荒谬的).