C++ - 在声明之外定义模板成员函数

标签 c++ templates overloading

我有一个模板结构,我想像这样“重载”:

#include <iostream>

template <typename T, typename U = int>
struct foo {
    void operator()(T, U);
}

template <typename T, typename U = int>
void foo::operator()(T a, U b){
    std::cout << "T, U ()\n";
}

template <typename T>
struct foo<T, int> {
    void operator()(T);
}

template <typename T>
void foo<T, int>::operator()(T a){
    std::cout << "T ()\n";
}

int main(int argc, char **argv){
    foo<int> a;
    foo<int, char> b;

    a(1);
    b(2, 'b');

    return false;
}

但是在编译时出现以下错误:

($ g++ test.cpp -o test)
test.cpp:11:6: error: 'template<class T, class U> struct foo' used without template parameters
test.cpp:11:30: error: 'void operator()(T, U)' must be a nonstatic member function

这很奇怪,因为 foo< T, int >::operator() 的定义似乎工作得很好。另外,当我像这样定义内联函数时:

template <typename T, typename U = int>
struct foo {
    void operator()(T a, U b){ std::cout << "T, U ()\n"; }
}

它没有问题。

最佳答案

您必须使用这些模板参数来指定哪个 foo,foo<T,U>::operator() .并从定义中删除默认模板参数值。

template <typename T, typename U>    // don't use a default parameter
void foo<T,U>::operator()(T a, U b){ // don't forget the <T,U> here
    std::cout << "T, U ()\n";
}

您还忘记了模板类定义后的分号。

关于C++ - 在声明之外定义模板成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201489/

相关文章:

c++ - 重载运算符 +。字符串类

ruby-on-rails - 从作为引擎安装的 gem 重载 lib 文件

c++ - 如何在构造函数调用中使用初始化列表来配置 `std::vector<std::vector<MyClass>>`?

带有模板化参数的 C++ 函数模板

c++ - 使用-O0优化对静态变量的 undefined reference [stm32模板引脚]

Django 没有在正确的目录中寻找模板

C++ 模板显式实例化

java:重载时返回类型不同

c# - C++ 与 C# - 数组

c++ - Vim 中智能缩进或文件类型缩进出现奇怪的缩进行为