apalomer
apalomer

Reputation: 1925

Using function templates instead of template specialization

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.

Upvotes: 2

Views: 80

Answers (2)

Oliv
Oliv

Reputation: 18051

Option N°2:

#include <iostream>

template <typename T>
void f(T val)
{
  std::cout << "generic" << val << std::endl;
}


void f(float val)
{
  std::cout << "Target specific" << val << std::endl;
}

int main()
{
  f(1); //=> generic
  f(1.0f); //=> target specific
  f<float>(1.0f); //=> generic
  return 0;
}

Upvotes: 2

user7860670
user7860670

Reputation: 37520

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

Upvotes: 7

Related Questions