C++模板专用化:编译错误:"is not a type"

C++ Template Specialization: compile error: "is not a type"

本文关键字:is not type 错误 编译 专用 C++      更新时间:2023-10-16

如果我删除模板专用化部分(尝试打印"Test 2"的部分),代码可以很好地编译,但我希望能够有一个特殊情况,运行不同的代码路径,对外部用户来说看起来很干净。

#include <iostream>
using namespace std;
struct SpecialType {};
template<typename A , typename B = SpecialType>
class Test
{
public:
    class TestInner
    {
    public:
        TestInner& operator* ();
    };
};
template<typename A , typename B>
typename Test<A , B>::TestInner& Test<A , B>::TestInner::operator* ()
{
    cout << "Test 1" << endl;
    return *this;
}
// If the following is removed, everything compiles/works, but I want this alternate code path:
template<typename A>
typename Test<A , SpecialType>::TestInner& Test<A , SpecialType>::TestInner::operator* ()
{
    cout << "Test 2" << endl;
    return *this;
}
int main()
{
    Test<int , SpecialType>::TestInner test;
    *test;
   return 0;
}

我做错了什么?

编辑:顺便说一下,编译器错误如下:

main.cpp:26:44: error: 'Test<A, SpecialType>::TestInner' is not a type
 typename Test<A , SpecialType>::TestInner& Test<A , SpecialType>::TestInner::operator* ()
                                            ^
main.cpp:26:89: error: invalid use of dependent type 'typename Test<A, SpecialType>::TestInner'
 typename Test<A , SpecialType>::TestInner& Test<A , SpecialType>::TestInner::operator* ()
                                                                                         ^

为专业类添加声明:

template<typename A>
class Test<A, SpecialType>
{
public:
    class TestInner
    {
    public:
        TestInner& operator* ();
    };
};

问题是您为未声明的专用化定义了一个成员。模板化类的专用化不与通用模板共享任何成员或方法,因此通用模板的声明不用作该模板类的任何专用化的声明。

考虑一下:

template <class T>
class Foo {
  void GeneralFunction(T x);
}

和专业化:

template <>
class Foo<int> {
  void SpecialisedFunction(int x);
}

在这里,Foo</*anything except int*/>只有方法GeneralFunctionFoo<int>只有方法SpecialisedFunction

按照同样的逻辑,这也是允许的:

template<>
class Foo<float> {
  float GeneralFunction; //here GeneralFunction is a data member, not a method.
}

长话短说,您需要声明您的专业化。

相关文章: