A related question is in C, but this questions pertains to specifically C++. When I try to compile this code, it gives me the following error message:
In file included from main.cpp:5:
./Any.hpp:20:6: error: function 'any<std::__1::vector<double, std::__1::allocator<double> >, (lambda at main.cpp:12:23)>' is used but not defined in this translation unit, and
cannot be defined in any other translation unit because its type does not have linkage
bool any(List &elements, Function callback);
^
main.cpp:19:9: note: used here
if (any(doubleElements, doubleFunc)) {
^
In file included from main.cpp:5:
./Any.hpp:20:6: error: function 'any<std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >, (lambda at main.cpp:15:23)>' is used but
not defined in this translation unit, and cannot be defined in any other translation unit because its type does not have linkage
bool any(List &elements, Function callback);
^
main.cpp:22:9: note: used here
if (any(stringElements, stringFunc)) {
^
2 errors generated.
Below are the source files:
Any.h
#ifndef ANY_HPP_INCLUDED
#define ANY_HPP_INCLUDED
/**
* @author Ben Antonellis
**/
#include <vector>
#include <iostream>
/**
* Returns True if any of the elements meet the callback functions parameters.
*
* @param elements - A list of elements.
* @param callback - Callback function to invoke on each element.
*
* @return bool - True if parameters are met, False otherwise.
**/
template <typename List, typename Function>
bool any(List &elements, Function callback);
#endif
Any.cpp
/**
* @author Ben Antonellis
**/
#include "Any.hpp"
template <typename List, typename Function>
bool any(List &elements, Function callback) {
for (auto element : elements) {
if (callback(element)) {
return true;
}
}
return false;
}
And here's how I'm calling this function:
main.cpp
/**
* @author Ben Antonellis
**/
#include "Any.hpp"
int main() {
std::vector<double> doubleElements = {-1.0, -2.0, -3.0};
std::vector<std::string> stringElements = {"Hello", "Goodbye", "Testing 123"};
auto doubleFunc = [] (double number) {
return number < 0;
};
auto stringFunc = [] (std::string string) {
return string.length() > 5;
};
if (any(doubleElements, doubleFunc)) {
std::cout << "Double Success." << std::endl;
}
if (any(stringElements, stringFunc)) {
std::cout << "String Success." << std::endl;
}
return 0;
}
This is the current way I am compiling my code:
g++ -std=gnu++2a -c main.cpp Any.cpp
Any help is appreciated, I've been stuck on this for a long time.