Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c++ - Avoid angle brackets in default template

If I have a template class with a default template type, I have to write the template angle brackets. Is it somehow possible to avoid this?

Example:

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 separate 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;
std::cout << t.get() << std::endl;

The problem is, if I want to use the class with an other type I have to go over namespace detail_. Is there another solution, which I didn't see yet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

... if I want to use the class ...

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 <typename>  class T>
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...