Reply to comment

Templated Constructors in C++: Using the "explicit" Keyword

Sometimes, in the course of C++ template based programming it might be desirable to have a constructor that is templated, like the following contrived exampled:

#include <iostream>
 
struct TestClass
{
  template<typename T>
    TestClass(const T &t)
    {
      std::cout << "Constructed a TestClass " << t << std::endl;
    }
};

By creating a templated constructor, however, we have created an infinite number of automatic type conversions. That is, the following code does compile:

void TakeATestClass(const TestClass &t)
{
}
 
int main()
{
  TakeATestClass("Bob");
}

Is the above something that we really expected to compile? Probably not, but even if it is, the chance that we will lose track of it down the road and it will come back to bite us is pretty high.

In fact, this takes principle #40 from C++ Coding Standards, "Avoid providing implicit conversions," and raises it to the Nth degree.

The solution is simple. We can still retain the flexibility of the templated constructor while eliminating the accidental conversions by adding the "explicit" keyword to our constructor.

struct TestClass
{
  template<typename T>
    explicit TestClass(const T &t)
    {
      std::cout << "Constructed a TestClass " << t << std::endl;
    }
};

Our new version should eliminate all unintended constructions of our new class.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
14 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.