I have a custom class encapsulating a std::tuple
("MyTuple") and another class implementing a custom interface for a std::tuple
("MyInterface"). I need this separate interface in the code base, the code below is simplified.
Since elements of std::tuple
need to be accessed with the key as template parameter, the interface's functions have a numeric template parameter size_t Key
which is then given to std::get
for the tuple for example.
This interface works fine, but not when calling it from another templated function which passes a numeric parameter as "key":
#include <iostream>
#include <functional>
#include <tuple>
#include <string>
template <typename... Types>
class MyInterface {
public:
MyInterface(const std::tuple<Types...>& tuple) : tuple(tuple) {}
template <size_t Key>
std::string getString() {
return std::to_string(std::get<Key>(tuple));
}
private:
const std::tuple<Types...>& tuple;
};
template <typename... Types>
class MyTuple {
public:
MyTuple(Types... values) : value(std::tuple<Types...>(values...)) {}
template <size_t Key>
std::string asString() {
MyInterface<Types...> interface(value);
return interface.getString<Key>(); // here I get the compiler error
}
private:
std::tuple<Types...> value;
};
int main() {
MyInterface<int, float, long> interface(std::tuple<int, float, long>(7, 3.3, 40));
std::cout << interface.getString<0>() << std::endl; // this works fine
MyTuple<int, float, long> tuple(7, 3.3, 40);
std::cout << tuple.asString<0>() << std::endl;
}
Complete output of g++:
templated_function_parameter_pack.cpp: In member function ‘std::__cxx11::string MyTuple<Types>::asString()’:
templated_function_parameter_pack.cpp:28:39: error: expected primary-expression before ‘)’ token
return interface.getString<Key>(); // here I get the compiler error
^
templated_function_parameter_pack.cpp: In instantiation of ‘std::__cxx11::string MyTuple<Types>::asString() [with long unsigned int Key = 0; Types = {int, float, long int}; std::__cxx11::string = std::__cxx11::basic_string<char>]’:
templated_function_parameter_pack.cpp:40:34: required from here
templated_function_parameter_pack.cpp:28:33: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘long unsigned int’ to binary ‘operator<’
return interface.getString<Key>(); // here I get the compiler error
Why is not valid syntax to call interface.getString<Key>()
inside MyTuple::asString<size_t Key>
?