Since I also encounter this problem now, and I canβt add an answer to another, but also valid, question asked here , I will give an example of solving the problem: getting only the line number where the function was called in C ++ using templates.
Background: in C ++, non-type integer values ββcan be used as an argument to a template. This differs from the typical use of data types as template arguments. Therefore, the idea is to use such integer values ββto call the function.
#include <iostream> class Test{ public: template<unsigned int L> int test(){ std::cout << "the function has been called at line number: " << L << std::endl; return 0; } int test(){ return this->test<0>(); } }; int main(int argc, char **argv){ Test t; t.test(); t.test<__LINE__>(); return 0; }
Output:
function is called in line number: 0
function is called in the line of number: 16
It is worth mentioning here that in C ++ 11 Standard, you can set default template values ββfor functions using the template. In pre C ++ 11, the default values ββfor non-type arguments seem to work only for template template arguments. Thus, in C ++ 11, there is no need to have duplicate function definitions, as described above. In C ++ 11, it is also valid for const char * arguments, but they cannot be used with literals like __FILE__ or __func__ , as mentioned here .
So in the end, if you are using C ++ or C ++ 11, this can be a very interesting alternative than using a macro to invoke the calling string.
John Doe Feb 09 '16 at 20:51 2016-02-09 20:51
source share