Consider the following template class:
//Node.hh
template<class dataType>
class impNode
{
private:
dataType _data;
public:
explicit impNode(const dataType &data) { std::cout << "this constructor is called!" << std::endl; };
virtual ~impNode() { };
dataType getData() { }; //This is where the error triggers
};
Now, when instantiating this class:
//main.cpp
int main(int, char**)
{
impNode a{98};
impNode b{false};
impNode c{"hello"};
}
I get the following compile time error:
error: function returning an array
[build] 27 | dataType getData() { };
One way to avoid this is to specialize the class template:
template<>
class impNode<char[6]>
{
private:
public:
explicit impNode(const char data[6]) { std::cout << "This class template specialization is needed for the program to compile" << std::endl; };
virtual ~impNode() { };
char* getData() { };
};
Doing so, the program compiles and runs successfully, being this the output of the program:
this constructor is called!
this constructor is called!
This class template specialization is needed for the program to compile
However I would like to be able to instantiate the class with any cstyle rvalue string without having to specialize for each different size.
CodePudding user response:
Just use auto:
auto getNode() { return _data; }
CodePudding user response:
You can provide a template deduction guide:
template<std::size_t N> impNode(char const (&)[N]) -> impNode<char const*>;
Or if you need to match any type instead of just char
:
template<typename T, std::size_t N> impNode(T const (&)[N]) -> impNode<T const*>;
However, it might just be easier to make getData
return a reference:
dataType& getData() { };