您可以通过其他方式使您的代码失败,从而使编译器输出您需要的信息。这可以例如在断言失败的情况下进行一些不完整的模板实例化。
例如,编译以下代码:
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;
}
在使用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;
^
所以gcc 现在告诉我函数调用是从我的main.cpp 文件的第18 行进行的,正确识别了有问题的行。
这应该能够提供您需要的信息。
编辑 15/12-15:
要打印编译时警告,您需要触发一个不会导致编译器错误的软错误。这可以例如成为溢出警告。
为了简短起见,代码如下所示:
///
// 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;
}
用gcc 编译这个给我:
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' 显示函数调用跟踪,以 main.cpp 的第 32 行结束。