[英]Template Instantiation Source file and Line Number, From where it is being called
在下面的代碼中:
template< typename T, typename ValueType>
bool SomeFunction(
SomeWrapper<T> volatile& ioTarget,
ValueType inCompare,
ValueType inNewValue)
{
BOOST_STATIC_ASSERT(sizeof(SomeWrapper<T>) == sizeof(int));
}
Boost Static Assert失敗,並出現編譯時錯誤。
獲得sizeof(T)幫助我在編譯時獲得警告的大小。
在分析Compiler Message時,它沒有精確指向進行此模板化調用的實際源代碼位置。
是否有任何其他這樣的模板化技術可用於從調用此函數的位置獲取有關實際源代碼文件和行的信息。
PS:我曾經考慮過__FILE__
,但是這在編譯時沒有幫助。
您可以通過其他某種方式使代碼失敗,從而使編譯器輸出所需的信息。 例如,這可以通過在斷言失敗的情況下執行一些不完整的模板實例化來實現。 作為示例,編譯以下代碼:
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); }
“清楚地”顯示了函數調用跟蹤,以main.cpp
第32行結尾。
我正在研究XCode 6.3 LLVM,它沒有給我失敗的確切行號。 但是在分析Compiler Logs時,它會在報告錯誤后告知此信息。
因此,只需查看錯誤后的日志即可解決此問題。 現在,我可以找到此實例。
但這仍然是一個懸而未決的問題,如果該模板已成功實例化,是否有任何元編程技術可以某種警告(不是錯誤)告訴您該模板已從X文件和Y行號實例化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.