【问题标题】:U does not name a type - template compilation errorU 没有命名类型 - 模板编译错误
【发布时间】:2021-09-21 07:25:59
【问题描述】:

这是我的简单程序。我尝试强制使用static_cast,以便编译器知道U 只不过是int。但是,模板仍然无法实例化我的函数 Add 的 int 版本。

将来,我想扩展这个模板,使U 和V 是不同的类型,我的程序仍然可以工作。

但是,目前,即使是相同的类型也无法正常工作。我在这里错过了什么?

编译错误的原因是什么?

#include <iostream>
using namespace std;

template <typename U>
class Addable
{
    U x;
public:
    Addable(U val) : x{ val } { cout << "Constructor called" << endl; }
    template <typename T>
    U add(T y);
};

U Addable::add(T y)
{
    x += y;
    return x;
}

int main()
{
    Addable<int> A{ 10 };
    int x = A.add(static_cast<int>(10));
    cout << x;
    return 0;
}

【问题讨论】:

标签: c++ c++11 templates member-functions class-template


【解决方案1】:

您的模板成员函数的定义是错误的。 定义模板类的模板成员函数时,需要指定两个模板参数,如下所示:

template <typename U>
template <typename T>
U Addable<U>::add(T y)
{
    x += y;
    return x;
}

live demo

【讨论】:

    【解决方案2】:

    为了在模板类之外定义模板函数。正确的应该是

    template <typename U> template <typename T>
    U Addable<U>::add(T y)
    {
       x += y;
       return x;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多