我在一個模塊內有一個向量類:
我在一個模塊內有一個向量類。
// other_library.cpp
module。
#include <iostream>
export module mylibrary.other;
export template< class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y){}。
void Write()
{
std::cout << "Vector{" << x << ", " << y << " }
"。
}
};
在main里面,我創建了一個向量并列印其內容:
// main.cpp
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write()。
return 0。
然而,我得到了意外的列印到終端的結果。
Vector{10x55a62f2f100c20x55a62f2f100f
這是使用的構建命令:
g -11 -std=c 20 -fmodules-ts -c other_library.cpp
g -11 -std=c 20 -fmodules-ts -c main.cpp
g -11 -std=c 20 -fmodules-ts *.o -o app
./app
自然地,如果我把矢量類移到主檔案中,列印就會如期進行。我知道模塊支持仍然有些實驗性。但我希望像這樣簡單的東西能直接作業。但也許我做錯了什么?
編輯:
一種蹩腳的破解方法是,在匯入模塊之前,在主檔案的頂部手動包含 iostream,就像這樣:
// main.cpp
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write()。
return 0。
這將正確列印Vector的內容。但是為什么要這樣做呢?把東西放在模塊中的目的是為了避免頭檔案的麻煩。
因此,我的問題現在是雙重的。
uj5u.com熱心網友回復:
這樣看來,模塊仍然存在一些挑戰。例如。我不能在Vector.Write成員函式中使用std::endl。
一個解決方案是預編譯iostream標準頭,可以這樣做:
g -11 -std=c 20 -fmodules-ts -xc - system-header iostream
預編譯的模塊將被保存在gcm.cached/目錄下,并且將成為連續的gcc-commands的隱含搜索路徑。
現在,我可以完全避免包括標準頭,所以庫檔案現在看起來是這樣的:
// other_library.cpp
export module mylibrary.other。
import <iostream> 。
export template< class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y){}。
void Write()
{
std::cout << "Vector{" << x << ", " << y << "}"
<< std::endl;
}
};
而且我不需要在主檔案中做任何進一步的作業--只要匯入我的庫模塊就足夠了。
非常感謝?imon Tóth在他的關于模塊的文章中寫到了這一點。
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/329618.html
標籤:
上一篇:如何在變數中存盤用指標參考的值?
