且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模板专用化或条件表达式?

更新时间:2023-11-27 18:41:22

速度并不是主要问题这里,但可扩展性。



专业化的优点是,您的代码的客户端更容易添加新的重载 foo() 。假设你以后决定在 i = 4 中添加新行为:在第一种方法中,你只需添加一个新的专门化;在第二个版本中,您需要修改函数 foo()。如果你已经以二进制形式发布了你的库,客户将不会很高兴。



专业化方法对第二种方法的偏好是开放/封闭原则的表现:代码应该打开以进行扩展,关闭进行修改。


I am deep into a new project which I address with a bunch of templates and specializations of them. Now, after a day without programming, I find myself asking whether it is really worth the extra lines of code.

The question is: What are the advantages of specialization?

Is this:

template <int i> class A {};
template <> class A <1> { void foo() {/* something */}  };
template <> class A <2> { void foo() {/* something else*/}  };
template <> class A <3> { void foo() {/* even different*/}  };

In any way better (faster execution) than

template <int i> class A { 
   void foo() {
      if (i==1) {/* something */}
      else if (i==2) {/* something else*/}
      else if (i==3) {/* even different*/}
   }
};

?

Edit:

The code is part of a library to be used by others. I am using gcc 4.6.3 but in the end the code will be used with different compilers.

Edit:

These two pieces of code result in identical binaries using gcc 4.6.3. I cannot test the full case as my actual code is far from being usable. It really seems to be a matter of principle, versatiliy, reusability, maintanability etc...

Speed is not the primary issue here, but extensibility is.

Specialization has the advantage that you make it easier for clients of your code to add new overloads of foo(). Suppose you later decide to add new behavior for i=4: in the first approach, you simply add a new specialization; in the second version, you need to modify the function foo(). If you have released your library in binary form, clients will not be happy.

The preference of the specialization approach to the second one is a manifestation of the Open/Closed Principle: code should be open for extension, closed for modification.