Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function templates instead of template specialization

Tags:

c++

templates

I am specializing template functions when intel intrinsic computation is available. In my case SSE and AVX. I want to produce a test program where I cal the non-specialized template function and the specialized one to compare performance. However, I do not know how to call the non-specialized template function for the type that it is specialized.

Here is a simplified example:

#include <iostream>

template <typename T>
void f(T val)
{
  std::cout << "Template function. Value: " << val << std::endl;
}

template <>
void f(float val)
{
  std::cout << "Float function. Value: " << val << std::endl;
}

int main()
{
  f(1);
  f(1.0f);
  return 0;
}

Question: is there a way to call f(1.0f) with the non-specialized template function without changing function names?

Clarification: In my case, the two functions are provided in a library as part of the same pair of header and implementation file. Then this is included (for the template) and linked (for the specialization) in the program.

like image 754
apalomer Avatar asked Nov 19 '25 11:11

apalomer


1 Answers

You can add an extra parameter to prohibit specialization:

#include <iostream>

template <typename T, bool enable_specialization = true>
void f(T val)
{
  std::cout << "Template function. Value: " << val << std::endl;
}

template <>
void f<float, true>(float val)
{
  std::cout << "Float function. Value: " << val << std::endl;
}

int main()
{
  f(1.0f);
  f<float, false>(1.0f);
  return 0;
}

online compiler

like image 56
user7860670 Avatar answered Nov 21 '25 23:11

user7860670



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!