Template - restrict type

Flaviu_ 1,031 Reputation points
2023-07-12T11:31:54.1366667+00:00

If I have a template function, how can I restrict this function to only two types, without using type_traits ?

#include <iostream>
#include <utility>
#include <type_traits>

template <typename T>
void swap_bytes(T& a, T& b)
{
	std::swap(a, b);
}

template <>
void swap_bytes(int& a, int& b)
{
	std::swap(a, b);
}

template <>
void swap_bytes(float& a, float& b)
{
	std::swap(a, b);
}

int main()
{
	int a{ 3 }, b{ 4 };
	swap_bytes(a, b);
	char c1{ 'q' }, c2{ 'r' };
	swap_bytes(c1, c2);  // works ! and it shouldn't !

	return 0;
}


As you see, I still can use this function with char type.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,829 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Flaviu_ 1,031 Reputation points
    2023-07-12T12:10:05.3066667+00:00
    template <typename T>
    void swap_bytes(T& a, T& b)
    ;
    
    template <>
    void swap_bytes(int& a, int& b)
    {
    	std::swap(a, b);
    }
    
    template <>
    void swap_bytes(float& a, float& b)
    {
    	std::swap(a, b);
    }
    
    int main()
    {
    	int a{ 3 }, b{ 4 };
    	swap_bytes(a, b);
    	char c1{ 'q' }, c2{ 'r' };
    	swap_bytes(c1, c2); // fatal error LNK1120
    
    	return 0;
    }
    
    
    

    I found it, just declare the template, not implement it.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.