具有不同主体的方法的模板显式实例化
Template explicit instantiation of a method with a different body
我有一个模板类,它有一个接受std::vector<T>
的构造函数。对于除一个对象外的每一个对象,我都希望它进行操作A。但对于这一个对象来说,我希望它做一些其他的事情B。
是否有可能只为模板类创建构造函数的显式实例化?我希望它描述得足够准确。
问候
更新:我现在已经实现了一个测试用例:
//header
Container(const std::vector<T>& source)
{...}
//source code
template <> Container<int>::Container(const std::vector<int>& source)
{
throw 42;
}
此示例可编译但不起作用。我将其导出到dll中,并希望每当我尝试用泛型参数int创建类的实例时都能调用它。但现在,它只调用用于其他所有对象的标准构造函数。我必须对申报单做些修改吗?
更新:我成功了!只需要将其复制到头文件中。
更新:好的,现在我有另一个问题。我能够为"简单"类型进行专门化,但不能为模板进行专门化。我是这样尝试的:
template<typename T>
Container<MyClass<T>>::Container(const std::vecror<MyClass<T>>& source)
{...}
我想为每个MyClass对象专门化它,但MyClass本身应该能够作为模板存在。
您的问题不清楚。也许你的意思是这样的?
template <typename T>
class Foo
{
public:
Foo() { std::cout << "standard" << std::endl; }
};
template <>
Foo<float>::Foo() { std::cout << "random" << std::endl; } // Special case
...
Foo<int> f1; // Prints "standard"
Foo<float> f2; // Prints "random"
哪个编译器?我在一些旧版本的g++编译器以及Solaris和HPUX c++编译器的模板实例化方面遇到了问题。template <>
用于指定显式通知。我已经很久没有专门化只一个类的方法了。
你试过了吗?
template <> TemplateClass<InstanciedType>::TemplateClass() {
...
}
其中,TemplateClass是要覆盖的模板类实例。
没有办法进行显式构造函数模板实例化——这里介绍了这一点:C++调用显式模板构造函数
如果我正确理解你的问题,你想这样做:
template< typename T >
struct A
{
template< typename P >
A( std::vector< P > &v )
{
}
};
相关文章:
- 使用动态实例化的对象填充矢量的快速方法
- 检查类是否在方法中实例化
- 从 c++ 中的实例化进程获取输出的可靠方法是什么?
- 使用包含互斥锁的类的方法实例化 cpp11 线程
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 当c++实例化方法?
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- C++ 实例化新对象时不接受继承方法默认参数值
- 实例化新类时未调用的方法
- 找不到使用 bitset 实例化模板函数的有效方法
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 有没有一种优雅的方法可以从 std::vector 实例化 boost::array
- 使用类方法而不实例化
- 一种安全、符合标准的方法,使类模板专用化仅在实例化时才无法使用"static_assert"进行编译
- C++17 单独的显式方法模板实例化声明和定义
- 如何实例化多个 set 对象来测试 Set 类的各种构造函数和方法
- 模板类方法的部分专用化或实例化
- 使用自动>decltype方法显式实例化函数
- 添加无模板实例化的访问者方法
- 在不实例化的情况下调用不同派生类的虚拟方法