我可以在不实例化模板类的情况下显式实例化模板类的模板成员吗?
Can I explicitly instantiate template member of template class without instantiating the template class?
我想显式实例化模板成员,但不实例化模板类。但是我收到编译器错误,所以这可能吗?这是我的代码:
//mytemplate.h
template <class T>
class mytemplate
{
public:
mytemplate(T* tt)
{
mT = tt;
}
template<class B>
void print(const B& bb);
T* mT;
};
//in mytemplate.cpp
#include "mytemplate.h"
template<typename T>
template<typename B>
void mytemplate<T>:: print(const B& bb)
{
B b = bb;
}
template<typename T> void mytemplate<T>::print<float>(const float&) const;
template<typename T> void mytemplate<T>::print<int>(const int&) const;
// main.cpp
int main()
{
int d =0;
mytemplate<int> k(&d);
k.print<float>(4.0);
}
使用模板,将问题分解为尽可能小的构建块总是有帮助的。 MyTemplate::p RINT可以通过调用模板自由函数来编写。
通过这种方式,您可以实现成员函数的部分专用化效果。
这里一个主要问题是"print(( 方法应该做什么?下面是一个示例,其中mytemplate<T>
为免费函数提供打印策略。当然,没有理由说该策略不可能是通过其他一些(可能是专门的(模板自由函数构建的其他类。
// Policy is a concept which supports 2 methods:
// print_prefix() and print_postfix()
//
template<class Policy, class B>
void print_with_policy(const Policy& policy, const B& value) const
{
policy.print_prefix();
cout << value;
policy.print_postifx();
}
template<class T>
struct mytemplate
{
// implement in terms of a free function
template<class B> void print(const B& value) {
print_with_policy(*this, value);
}
// policy concept implementation
void print_prefix() const {
cout << "prefix-";
}
void print_postfix() const {
cout << "-postfix";
}
};
扩展示例以使用具有字符串专用的单独策略类:
template<typename B>
struct default_policy {
default_policy(const B& value) : _value(value) {}
void operator()() const {
cout << "(" << _value << ")";
}
private:
const B& _value;
};
template<typename B>
struct quoted_policy {
quoted_policy(const B& value) : _value(value) {}
void operator()() const {
cout << '"' << _value << '"';
}
private:
const B& _value;
};
template<class B>
default_policy<B> make_policy(const B& value) {
return default_policy<B>(value);
}
// overload for B being a string
quoted_policy<std::string> make_policy(const std::string& value) {
return quoted_policy<std::string>(value);
}
template<class T>
struct mytemplate
{
// implement in terms of a free function
template<class B> void print(const B& value) {
make_policy(value)();
cout << endl;
}
};
int main()
{
struct foo{};
mytemplate<foo> fooplate;
fooplate.print(int(8));
fooplate.print(std::string { "a string" });
fooplate.print("not a string");
return 0;
}
输出:
(8)
"a string"
(not a string)
相关文章:
- 静态数据成员模板专用化的实例化点在哪里
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 受约束的成员函数和显式模板实例化
- 实例化多种类型的成员函数模板
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- 将类成员函数的模板定义放在 CPP 文件中C++隐式实例化而不是 .H 允许吗?
- 如何实例化类的公共成员并将其作为 std::p romise 返回?
- 在实例化封闭类模板之后,我们可以声明模板类成员的部分专用化吗
- 使用 SFINAE 有选择地实例化模板的成员函数
- 静态模板成员函数的实例化?
- 访问使用接口实例化的类的私有成员
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 参考数据成员到模板的实例化
- 类的私有成员在我的类实例化期间更改,即使他们不应该
- 如果未实例化成员模板,是否要评估static_asserts?
- 实例化与unique_ptr的类集合成员
- 实例化成员模板函数时的Buggy(?)编译器行为
- 类模板的成员函数模板找不到定义,尽管存在显式实例化。不链接
- 如何实例化C++成员字符串引用
- 通过模板参数选择子类与实例化成员变量的区别