c++ - 为什么将 '<' 当作 'operator<' 而不是一个标记来包围模板参数呢?

标签 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;
}

我在用 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);
            ^

为什么需要 <作为operator<而不是包含模板参数的标记?

最佳答案

因为代码本质上是不明确的1 所以编译器必须决定哪一种方式。 C++ 标准委员会武断地决定,如果有疑问,假设名称是变量,而不是类型

如果你希望你的代码被解析为一个模板,你需要明确说明:

t.template f<SIZE>(x);

1 在解析此代码时,t 的类型尚不清楚,因为它是一个模板。考虑以下类型:

struct T {
    int f;
};

如果您现在用该类型实例化 A,您将得到(伪代码,因为模板已实例化):

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

为了澄清,我添加了括号:这就是编译器如何看待您的代码,并且它是完全有效的(尽管毫无意义)。

关于c++ - 为什么将 '<' 当作 'operator<' 而不是一个标记来包围模板参数呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865018/

相关文章:

templates - Chef 模板 - 有条件地插入文本 block

c++ - C++ 模板中的代码重用(或不重用)

c++ - 如何使用 C++ 在 Vista 中将窗口置于前台?

c++ - 如何将 'convert' 的 Hz 量转换为适当的字节/位格式?

c++ - Windows Mobile 命令行编译器

c++ - 为什么 unique_ptr<Derived> 隐式转换为 unique_ptr<Base> ?

c++ - 调用指向成员函数的模板指针

c++ - 模板化运算符[] ...可能吗?有用?

c++ - 从 C++ 调用 Matlab 函数

c++ - 使用 MinGW 构建 ASSIMP 会导致文件太大错误