how to pass a char array to a template function

I am creating a simple program to output the position in the array of a char which the user inputs. If its not in the array, then "This value was not found in the array" will be outputted.

I have two template functions in a header file. One to display the contents of the array and one to find the position of the value in the array.

The problem is that it works fine when I send an array of integers too the functions in the header file but when I try send a char array, it gives me errors

error C2672: 'arrayLocation': no matching overloaded function found
error C2672: 'displayArray': no matching overloaded function found
error C2782: 'void displayArray(const T [],const T)': template parameter 'T' is ambiguous
error C2782: 'int arrayLocation(const T [],const T,const T)': template parameter 'T' is ambiguous
error C2784: 'void displayArray(const T [],const T)': could not deduce template argument for 'const T' from 'const int'
error C2672: 'arrayLocation': no matching overloaded function found

here is what I have so far
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//main.cpp

#include <iostream>
#include "locate.h"
using namespace std;

typedef char ItemType;

int main()
{
	const int arraySize = 10;
	ItemType array1[arraySize] = { 'a','b','c','d','e','f','g','h','i','j'};

	cout << "The values in the array as are follows: \n";

	displayArray(array1, arraySize);

	ItemType target;
	cout << "Enter a Value currently in the Array: ";
	cin >> target;

	int result = arrayLocation(array1, arraySize, target);

	if (result != -1)
		cout << "\n\nThe Value " << target << " was found at location "
		<< result << endl;
	else
		cout << "\n\nThe Value " << target << " was NOT found in the array" << endl;

	
	
	return 0;
}

//locate.h

#pragma once

template <typename T>

void displayArray(const T array1[],const T size)
{

	for (int i = 0; i < size; i++)
	{
		cout << array1[i] << endl;

	}

}
 
template <typename T>

int arrayLocation(const T array1[],const T size,const T target)
{
	int count = 0;

	for (int i = 0; i < size; i++)
	{
		count++;

		if (target == array1[i])
		{
			return count;

		}
	
	}
	
	if (count == size)
	{
		return -1;
	}
}


I may also add that when I pass an array of integers, it works perfectly however it gives me a warning 'arrayLocation<int>':not all control paths return a value' why is this?
1
2
template <typename T>
int arrayLocation(const T array1[],const T size,const T target)


Should the formal parameter size really be a T?

Last edited on
Topic archived. No new replies allowed.