如何使用类型名对结构进行前向声明?
How do I do a forward declaration of a struct with a typename?
我正在尝试在 C++ 中对具有类型名的结构进行前向声明。这样的事情是完全有效的:
typedef struct foo foo;
struct foo{
int f;
};
我的结构只是有一个类型名,所以我尝试了这个:
template <typename T>
typedef struct mV<T> mV;
template <typename T>
struct mV{
//contents of struct
};
但是,我随后收到错误 a typedef cannot be a template
、explicit specialization of undeclared template struct
和 redefinition of 'mV' as different kind of symbol
。我该如何解决这个问题?
您描述的是前向声明。 (future
在现代 C++ 中是完全不同的东西)。
typedef
在 C++ 中,不需要也很少需要别名结构标记。相反,您只需声明 class 类型并完成它。
// typedef struct mV mV; // not this
struct mV; // instead this
模板也是如此
template<class T>
struct mV;
如果您 need/want 附加一个 alias to your template type,您仍然可以通过 using
template<class T>
struct mV;
template<class T>
using MyAliasNameHere = mV<T>;
有了所有这些,并开始我推测您会在短期内发现的东西,您可能还需要阅读这篇文章:Why can templates only be implemented in header files?。有些东西告诉我这将变得高度相关。
我正在尝试在 C++ 中对具有类型名的结构进行前向声明。这样的事情是完全有效的:
typedef struct foo foo;
struct foo{
int f;
};
我的结构只是有一个类型名,所以我尝试了这个:
template <typename T>
typedef struct mV<T> mV;
template <typename T>
struct mV{
//contents of struct
};
但是,我随后收到错误 a typedef cannot be a template
、explicit specialization of undeclared template struct
和 redefinition of 'mV' as different kind of symbol
。我该如何解决这个问题?
您描述的是前向声明。 (future
在现代 C++ 中是完全不同的东西)。
typedef
在 C++ 中,不需要也很少需要别名结构标记。相反,您只需声明 class 类型并完成它。
// typedef struct mV mV; // not this
struct mV; // instead this
模板也是如此
template<class T>
struct mV;
如果您 need/want 附加一个 alias to your template type,您仍然可以通过 using
template<class T>
struct mV;
template<class T>
using MyAliasNameHere = mV<T>;
有了所有这些,并开始我推测您会在短期内发现的东西,您可能还需要阅读这篇文章:Why can templates only be implemented in header files?。有些东西告诉我这将变得高度相关。