如何转发声明 C++ 模板类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13848451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to forward declare a C++ template class?
提问by Tron Thomas
Given a template class like the following:
给定一个模板类,如下所示:
template<typename Type, typename IDType=typename Type::IDType>
class Mappings
{
public:
...
Type valueFor(const IDType& id) { // return value }
...
};
How can someone forward declare this class in a header file?
有人如何在头文件中转发声明此类?
回答by Pubby
This is how you would do it:
这是你会怎么做:
template<typename Type, typename IDType=typename Type::IDType>
class Mappings;
template<typename Type, typename IDType>
class Mappings
{
public:
...
Type valueFor(const IDType& id) { // return value }
...
};
Note that the default is in the forward declaration and not in the actual definition.
请注意,默认值在前向声明中,而不是在实际定义中。
回答by Dietmar Kühl
You can declare default arguments for a template only for the first declaration of the template. If you want allow users to forward declare a class template, you should provide a forwarding header. If you want to forward declare someone else's class template using defaults, you are out of luck!
您只能为模板的第一个声明声明模板的默认参数。如果你想让用户转发声明一个类模板,你应该提供一个转发头。如果您想使用默认值转发声明其他人的类模板,那您就不走运了!
回答by Elliott
Also, if you want to declare anything that belongs to a namespace then you must declare it withinthat namespace.
此外,如果您想声明属于命名空间的任何内容,则必须在该命名空间内声明它。
Eg. Declaring std::array
:
例如。声明std::array
:
This won't compile:
这不会编译:
template<class, long unsigned int>
struct std::array;
But this will work:
但这会起作用:
namespace std
{
template<class, long unsigned int>
struct array;
}
Also, you can declare a templated class even if its definition states the default arguments, but any time you reference the class you must include all of its arguments until the definition is introduced.
此外,您可以声明模板化类,即使其定义声明了默认参数,但任何时候引用该类时,您都必须包含其所有参数,直到引入定义为止。
eg. Let's use std::vector
without including it (the second argument of std::vector
is defined with a default):
例如。让我们在std::vector
不包含它的情况下使用(std::vector
使用默认值定义的第二个参数):
namespace std
{
template<class, class>
class vector;
}
#include <iostream>
template <class S, class T>
void Foo (const std::vector<S,T> & vector)
{
std::cout << "do vector stuff, eg., display size = "
<< vector.size() << std::endl;
}
template <class T>
void Foo (const T & t)
{
std::cout << "do non-vector stuff..." << std::endl;
}
We can then use it without including the vector, eg.:
然后我们可以在不包含向量的情况下使用它,例如:
int main()
{
int k = 3;
Foo(k);
return 0;
}
And we can use it withstd::vector
, eg.:
我们可以将它与 一起使用std::vector
,例如:
#include <vector>
// Now the compiler understands how to handle
// std::vector with one argument
// (making use of its default argument)
int main()
{
std::vector<int> k(3);
Foo(k);
return 0;
}