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

时间:2012-11-02 19:02:53

标签: 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&lt; T,int&gt; :: operator()似乎完美无缺。另外,当我像这样定义内联函数时:

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

没有问题。

2 个答案:

答案 0 :(得分:2)

您必须使用这些模板参数来指定哪个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";
}

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

答案 1 :(得分:0)

您只能在函数原型上指定一次默认模板参数(如果该函数具有原型)。

template <typename T, typename U = int> void f();
// ....

template <typename T, typename U = int> void f() {}

这是不必要的。简单地说:

template <typename T, typename U> void f() {}