Nigel Tiany
Nigel Tiany

Reputation: 71

How to get variable name from template g++

How can i get/print variable name from this? I am using arduino Stream to print to console.

#ifndef any_h
#define any_h

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

struct any {
  any(Stream& s):serial(s){}
  template <class T>
  void print(const T& msg)
  {
    getName(class T);
    serial.print(msg);
  }

  template <class A, class... B>
  void print(A head, B... tail)
  {
    print('{');
    print(head);
    print(tail...);
  }

  private:
    Stream& serial; 

};

#endif

Usage:

any A(Serial);

int myInt =34;
float myFloat = 944.5555f;
String myString = " this string";
A.print(myInt,myFloat,myString);

current output

34944.555 this string

I am trying to get something like with the same usage/access or like in this: Demo.

{"variableName":value,"variableName":value}
// That is in this case:
{myInt:34,myFloat:944.55,myString: this string}

What i have already tried:

#define getName(x) serial.print(#x)
void print(const T& msg)
{  
   getName(msg);
   //getName(class T);
   serial.print(msg);
}
output : msg34msg944.555msg this string

Upvotes: 0

Views: 1352

Answers (2)

Max Lybbert
Max Lybbert

Reputation: 20039

C++ doesn't have reflection, so you're limited to using macros, such as:

#include <iostream>
#define STRINGIFY_IMPL(X) #X
#define STRINGIFY(X) STRINGIFY_IMPL(X)
#define VARIABLE_NAME(X) STRINGIFY(X)
#define VARIABLE_VALUE(X) X

int main()
{
    double d = 3.141;
    std::cout << VARIABLE_NAME(d) << ": " << VARIABLE_VALUE(d) << '\n';
    return 0;
}

(VARIABLE_NAME and VARIABLE_VALUE aren't truly needed, you could also use std::cout << STRINGIFY(d) << ": " << d << '\n';).


You can, of course, combine this all into a super macro (with macros from above):

#include <iostream>
#include <string>
#define STREAM_NAME_VALUE(str, X) str << '{' << STRINGIFY(X) << ':' << X << '}'

int main()
{
    int myInt =34;
    float myFloat = 944.5555f;
    std::string myString = " this string";

    STREAM_NAME_VALUE(std::cout, myInt);
    std::cout << '\n';
    STREAM_NAME_VALUE(std::cout, myFloat);
    std::cout << '\n';
    STREAM_NAME_VALUE(std::cout, myString);
    std::cout << '\n';
    return 0;
}

Upvotes: 0

Fabricio
Fabricio

Reputation: 3297

You can use macro to do that combined with stringify preprocessor:

Code:

#include <stdio.h>

#define PRINT_NAME(name) print_name(#name, (name))

void print_name(char *name, char* value) {
    printf("name: %s ---> value: %s\n", name, value);
}

int main (int argc, char* argv[]) {
    char* var1 = 'my var 1';
    char* var2 = 'my new var 2';

    PRINT_NAME(var1);
    PRINT_NAME(var2);

    return 0;
}

Output:

name: var1 --> value: my var 1
name: var2 --> value: my new var 2 

I hope this helps :)

Upvotes: 3

Related Questions