避免在默认模板中使用尖括号 [英] avoid angle brackets in default template
问题描述
如果我有一个模板类与默认模板类型,但我必须写模板尖括号。 是否有可能避免此问题?
if i have a template class with a default template type, however i have to write the template angle brackets. is it possible to avoid this?
例如:
template <typename T=int>
class tt {
public:
T get() { return 5; }
};
...
tt<> t; // how to avoid <>
std::cout << t.get() << std::endl;
到目前为止,我已经通过一个单独的命名空间并重新声明了类:
until now i've did this by a seperate namespace and redeclaring the class:
namespace detail_ {
template <typename T=int>
class tt {
public:
T get() { return 5; }
};
}
class tt : public detail_::tt {}
...
tt t; // now it works
std::cout << t.get() << std::endl;
问题是,如果我想使用其他类型的类,我必须去namepace detail_。 是有其他解决方案,我还没有看到。
the problem is, if i want to use the class with an other type i have to go ov er namepace detail_. is there an other solution, wich i didn't see yet.
推荐答案
。 ..如果我想使用类...
这是一个常见的混乱来源。类模板不是类,而是生成类的模板。尖括号是告诉编译器,要使用给定的模板参数生成类模板中的类,而不使用尖括号您将是一个模板。
This is a common source of confusion. A class template is not a class, but a template from which classes are generated. The angle brackets is what tells the compiler that you want to generate a class out of the class template with the given template arguments, without the angle brackets what you have is a template.
template <typename T = int>
struct TemplateClass {...};
template <template class T<typename> >
void f() {
T<int> t; ...
}
template <typename T>
void g() {
T t; ...
}
f<TemplateClass>(); // Accepts a template with a single type argument
g<TemplateClass<> >(); // Accepts a type, that can be generated out of the template
语言不允许共存的模板和在同一命名空间中具有相同名称的类型,因此答案是它不能完成。您可以创建类型别名,但必须为其指定其他名称。
The language does not allow the coexistence of a template and a type with the same name in the same namespace, so the answer is that it cannot be done. You can create a type alias but you will have to give it a different name.
这篇关于避免在默认模板中使用尖括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!