0

这编译:

template <class T>
class Bar {};

template<class T, class Dummy=void>
class Foo;

template<class T>
class Foo <T, typename std::enable_if<
    std::is_base_of<Bar<T>, T>::value
>::type> {
    public:
        //THIS CHANGES IN THE 2ND SNIPPET
        void test () const {
            std::cout << "test";
        }
};

class Cat : Bar<Cat> {};

int main () {
    Foo<Cat> foo;
    foo.test();
    return 0;
}

这个错误:

template <class T>
class Bar {};

template<class T, class Dummy=void>
class Foo;

template<class T>
class Foo <T, typename std::enable_if<
    std::is_base_of<Bar<T>, T>::value
>::type> {
    public:
        //THIS CHANGED!
        void test () const;
};

//THIS WAS ADDED SINCE THE 1ST SNIPPET!
template<class T>
void Foo<T>::test () const {
    std::cout << "test";
} //error C2039: 'test' : is not a member of 'Foo<T>'

class Cat : Bar<Cat> {};

int main () {
    Foo<Cat> foo;
    foo.test();
    return 0;
}

我已经标记了差异。为什么它在第二个代码片段中出错?如何在避免错误的同时保持声明和定义分开?

我猜这与此有关:“template void Foo::test () const”

就像,这是告诉编译器方法test() const模板类 template class Foo 的方法的错误方法, T>::value >::type>

当然,我已经在 Google 和 StackOverflow 上进行了查找,但似乎每当模板出现此错误时,每次都是不同的原因。(可能因为很多事情都会导致C2039错误。)

Also, could a mod. or someone help me add the C2039 tag to this post? It says I need a min. of 1500 rep. to add that tag.

-- Rambling -- It also be noted that it's been a while since I've used C++; and even longer since I've used templates. I know this might be a weird way to use templates but I can assure you I have a valid reason!

4

1 回答 1

1

14.5.4.3/1 (C++03) 中给出了部分特化类模板的类外成员声明示例。这就是它的样子

// primary template
template<class T, int I> struct A {
  void f();
};

// class template partial specialization
template<class T> struct A<T,2> {
  void g();
};

// member of class template partial specialization
template<class T> void A<T,2>::g() { }

如您所见,您必须在类外成员定义中指定专门的参数。

在你的情况下,它应该是

template<class T>
void Foo<T, typename std::enable_if<
  std::is_base_of<Bar<T>, T>::value>::type>::test () const {
    std::cout << "test";
}
于 2013-07-07T04:36:08.640 回答