[英]assigning local variable to global variable in c++
我有對象
template <class FLOAT>
struct Cstruct {
Struct1<FLOAT> _var1;
Struct2<FLOAT> _var2;
Cstruct(){};
Cstruct(Struct1 var1,Struct2 var2):_var1(var1),_var2(var2){};
};
FLOAT可以是“ double”或“ int”。 Struct1和Struct2也用FLOAT進行模板化。
現在我也聲明了一個全局變量
Cstruct<double> globalObj_d;Cstruct<int> globalObj_i;
在main()內部
main(){
// some code
if double then call func<double>();
if int then call func<int>();
}
和內部的模板化func()
template<class FLOAT> void func(){
// some code
Struct1<FLOAT> var1;
Struct2<FLOAT> var2;
Cstruct<FLOAT> localObj(var1,var2);
// now i want to assign "localObj" to the global object "globalObj_d"
if double then
globalObj_d = localObj;
if int then
globalObj_i = localObj;
}
我得到一個錯誤的說法
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Cstruct<FLOAT>
這是否意味着我必須在Cstruct中顯式編寫一個“ operator =“? 我對模板化和全局對象的理解似乎有點缺陷。 任何幫助將不勝感激。
在您的問題中使用偽代碼很難理解。 因此,讓我嘗試將其歸結為實際代碼。 看來您嘗試做的事情本質上符合以下幾方面:
template <typename VAL>
class Foo
{
public:
VAL mVal;
};
int main()
{
Foo <int> global_i;
Foo <double> global_d;
Foo <double> local;
// ...
if (/*someConditional*/)
global_i = local; // <== LINE 1
else
global_d = local; // <== LINE 2
}
這行不通。 請注意,即使在運行時僅執行LINE1
或LINE2
之一,它們都在編譯時進行編譯。 第一個嘗試將Foo<int>
分配給Foo<double>
,但是類型不兼容,方式與它們也不兼容相同:
class Gee
{
};
class Whiz
{
};
int main()
{
Gee g;
Whiz w;
Gee local;
local = w; // <<< INCOMPATIBLE TYPES
}
為了使此工作有效,您要么需要在Foo
上提供某種轉換操作符,然后才能轉換為另一種Foo
類型,例如:
template <typename VAL>
class Foo
{
public:
template <typename OTHER> operator Foo <OTHER> () const
{
Foo <OTHER> ret;
// ...
return ret;
}
};
...或者可能提供兩個單獨的功能來進行分配; 一個用於Foo<int>
,另一個用於Foo<double>
。
第一:如果類型可以是浮點數或整數, 則不要將其命名為“ FLOAT”。 您可以使用標准T
,也可以使用諸如Number
東西,但絕對不要使用FLOAT
。
關於真正的問題(或我對真正問題的猜測):幾乎任何時候您都在考慮if (type == X)
或switch (type)
類代碼(至少在C ++中),基本錯誤-如果您想做的足夠糟糕, 可以設法做到這一點, 但這不是C ++的工作原理。
在這種情況下,有一種避免這種情況的簡單方法:創建另一個模板。 特別是,您可以重載幾個功能模板,每個要支持的全局模板一個:
#include <string>
#include <iostream>
int i_global;
double d_global;
template <class T>
void assign(T in) {
// this function should never be called.
assert(false);
}
template<>
void assign<int>(int in) {
i_global = in;
}
template<>
void assign<double>(double in) {
d_global = in;
}
// for the moment, func(input) will just call assign(input):
template <class T>
void func(T input) {
assign<T>(input);
}
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Usage: trash <number>\n";
return EXIT_FAILURE;
}
std::string in(argv[1]);
// see if the input contains a decimal point, and act accordingly:
if (in.find('.') != std::string::npos)
func(std::stod(in));
else
func(std::stoi(in));
// show the results -- the values of the globals:
std::cout << "Result:\ndouble: " << d_global << "\nint: " << i_global << "\n";
return 0;
}
我得到了我希望的結果-如果我輸入1.5
它將被分配給double; 如果我輸入類似123
它將被分配給int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.