You can make your code fail in some other way that makes the compiler output the information you need. This could e.g. be by doing some incomplete template instantiation in case of a failed assertion.
As and example, compiling the following code:
template<bool>
struct tester;
template<>
struct tester<true> { }; // only define template for 'true'
template<class T>
void func(T t)
{
tester<sizeof(T) == sizeof(int)>();
}
int main()
{
int i;
func(i); // <- this call is ok :)
double d;
func(d); // <- this is line 18, the offending call :(
return 0;
}
Gives me the following output, when compiling with gcc
:
g++-4.9 -O3 -fexpensive-optimizations -Drestrict= -std=c++11 -o main main.cpp -pthread
main.cpp: In instantiation of ‘void func(T) [with T = double]’:
main.cpp:18:10: required from here
main.cpp:10:4: error: invalid use of incomplete type ‘struct tester<false>’
tester<sizeof(T) == sizeof(int)>();
^
main.cpp:2:8: error: declaration of ‘struct tester<false>’
struct tester;
^
So gcc
now tells me that the function call was made from line 18 in my main.cpp
file, correctly identifying the offending line.
This should be able to give the information you need.
EDIT 15/12-15:
To print a compile-time warning you need to trigger a soft error, which does not result in a compiler error. This could e.g. be an overflow warning.
To keep it short, the code would look something like this:
///
// struct that will overflow and print integer s at compile-time
////
template<unsigned s>
struct overflow
{
operator char() { return (s + 256); }
};
/////
// function that will print warning message at compile-time
// warning message must be made as a class/struct
////
template<class MESSAGE>
void print_warning(MESSAGE)
{
char(overflow<sizeof(MESSAGE)>());
};
struct this_is_a_warning // warning message
{
};
template<class T>
void func()
{
print_warning(this_is_a_warning()); // <- this will print a warning, line 27
}
int main()
{
func<double>(); // <- line 32
return 0;
}
Compiling this with gcc
gives me:
g++-4.9 -O3 -fexpensive-optimizations -Drestrict= -std=c++11 -o main main.cpp -pthread main.cpp: In instantiation of ‘overflow<s>::operator char() [with unsigned int s = 1u]’:
main.cpp:17:4: required from ‘void print_warning(MESSAGE) [with MESSAGE = this_is_a_warning]’
main.cpp:27:37: required from ‘void func() [with T = double]’
main.cpp:32:17: required from here
main.cpp:7:37: warning: overflow in implicit constant conversion [-Woverflow]
operator char() { return (s + 256); }
'Clearly' showing showing the function call trace, ending with line 32 of main.cpp
.