re: your OP: I'd like to know why a couple of them failed.
The comment by @NatanReed is correct:
- Your first snippet fails because
Get
needs a TYPE
and is given an object
.
- Your second snippet fails because it is illegal to define a template argument as reference to an object.
- until C++2003, that is. Then
reference to an object
became legal.
Template arguments must be constants from a limited set of types.
- See: ISO/IEC 14882-2003 §14.1: Template parameters
- See: ISO/IEC 14882-2003 §14.3.2: Template non-type arguments
And even then, the String constexpr str = "hello";
must have external linkage. So putting it on the stack inside of main()
is not going to work.
Give this a try:
#include
#include
using namespace std;
struct String {
char const *m_sz;
constexpr String(char const *a_sz)
:
m_sz(a_sz) {}
};
template
string const Get() {
return _rstr.m_sz;
}
extern String constexpr globally_visible_str = "hello";
int main() {
cout << Get() << endl;
return 0;
}