- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
假设我们有以下文件:
foo.h
namespace ns
{
template <typename T>
class Foo
{
public:
Foo();
~Foo();
void DoIt();
};
}
foo.cpp
#include "foo.h"
#include <iostream>
namespace ns
{
template <typename T>
Foo<T>::Foo() { std::cout << "Being constructed." << std::endl; }
template <typename T>
Foo<T>::~Foo() { std::cout << "Being destroyed." << std::endl; }
template <>
void Foo<int>::DoIt()
{
std::cout << "Int" << std::endl;
}
template <>
void Foo<double>::DoIt()
{
std::cout << "Double" << std::endl;
}
template class Foo<int>;
template class Foo<double>;
}
假设该类型只会与 int 或 double 作为类型参数一起使用,这是进行显式实例化的正确方法吗?或者您是否也需要在头文件中声明显式特化?
按照我展示的方式使用 visual studio 进行操作,但一位同事在使用 GCC 时遇到了问题(虽然我刚刚检查过,我认为这是由于其他原因,但我还是会发布这个问题)
最佳答案
[temp.expl.spec]/p6(强调我的):
If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
事实上,如果将它们组合在一个 TU 中,clang 和 gcc will issue an error .您需要声明这些明确的特化。
因为我们真的很接近它,所以我也会引用 [temp.expl.spec]/p7,因为我可以:
The placement of explicit specialization declarations for function templates, class templates, variable templates, member functions of class templates, static data members of class templates, member classes of class templates, member enumerations of class templates, member class templates of class templates, member function templates of class templates, static data member templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, static data member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.
关于c++ - 如何正确地显式实例化具有完全特化成员的模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635532/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!