Я пишу общую библиотеку.Идея заключается в следующем: общая функция внутри библиотеки будет вызываться с параметром int или double.Он должен принять оба.В какой-то момент в функции есть вызов «закрытой» функции, которая делает что-то с параметром в зависимости от того, является ли он целым или двойным.Я решил использовать шаблон для функции библиотеки.Если я правильно понимаю, компилятор должен знать тип параметра, иначе он не сможет скомпилировать библиотеку.Поэтому я создаю два шаблона: один для int и один для double.Проблема в том, что компилятор, похоже, не знает, какую версию закрытой функции следует вызывать, хотя он знает тип ее параметра.
Уже поздно, я не знаю, что может бытьНеправильно, пожалуйста, помогите мне: -)
Петр
library.hpp
#include < iostream >
namespace {
void printNumber(int const n);
void printNumber(double const n);
}
namespace library {
template < typename T >
void doSomething(T const number);
}
library.cpp
#include "library.hpp"
using namespace std;
void printNumber(int const n) {
cout << "This was an int." << endl;
}
void printNumber(double const n) {
cout << "This was a double." << endl;
}
template < typename T >
void library::doSomething(T const number) {
// ...
// Do something that does not depend on T at all...
// ...
printNumber(number);
}
template void library::doSomething(int const number);
template void library::doSomething(double const number);
Main.cpp
#include "library.hpp"
int main(int const argc, char const * (argv) []) {
library::doSomething(10);
library::doSomething(10.0);
return 0;
}
Компилятор
../src/library.cpp: In function ‘void library::doSomething(T) [with T = int]’:
../src/library.cpp:21:52: instantiated from here
../src/library.cpp:18:2: error: call of overloaded ‘printNumber(const int&)’ is ambiguous
../src/library.cpp:5:6: note: candidates are: void printNumber(int)
../src/library.cpp:9:6: note: void printNumber(double)
/home/petmal/Eclipse_Projects/library/include/library.hpp:6:6: note: void::printNumber(double)
/home/petmal/Eclipse_Projects/library/include/library.hpp:5:6: note: void::printNumber(int)
../src/library.cpp: In function ‘void library::doSomething(T) [with T = double]’:
../src/library.cpp:22:55: instantiated from here
../src/library.cpp:18:2: error: call of overloaded ‘printNumber(const double&)’ is ambiguous
../src/library.cpp:5:6: note: candidates are: void printNumber(int)
../src/library.cpp:9:6: note: void printNumber(double)
/home/petmal/Eclipse_Projects/library/include/library.hpp:6:6: note: void::printNumber(double)
/home/petmal/Eclipse_Projects/library/include/library.hpp:5:6: note: void::printNumber(int)