簡體   English   中英

c ++:類的通用getter

[英]c++ : Universal getter for class

我需要幫助! 我想為我的類定義一個模板方法來訪問它的私有字段。 這是我的代碼:

#include <string>
#include <vector>
using namespace std;

class ex
{
public:
    ex(string pegah_,int amin_):pegah(pegah_),amin(amin_){}
    template<typename T>
    T get_field(){
        if(is_same<T,string>::value)
            return pegah;
        else if(is_same<T,int> ::value)
            return amin;
    }
private:
    string pegah;
    int amin;
};

int main(void)
{
    string i = "salam";
    int o=10;
    ex y(i,o);
    y.get_field<string>();
}

如你所見,我只想使用一個功能。 但我一直收到這個錯誤:

test.cpp: In instantiation of ‘T ex::get_field() [with T = std::basic_string<char>]’:
test.cpp:30:21:   required from here
test.cpp:15:8: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]
 return amin;
        ^
In file included from /usr/include/c++/4.8/string:52:0,
                 from test.cpp:1:
/usr/include/c++/4.8/bits/basic_string.h:490:7: error:   initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ [-fpermissive]
       basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());

有人可以幫忙嗎?

相反,您可以像這樣放置代碼:

template<typename T> T get_field();

// outside the class:
template<> inline int ex::get_field<int>() { return amin; }
template<> inline string ex::get_field<string>() { return pegah; }

正如你現在所擁有的那樣, if..else所有分支都必須編譯。

基本上你有三種選擇。

首先使用模板成員函數的顯式特化。

class Foo {
public:
    template <typename T>
    T get () const;

private:
    std::string str {"XXX"};
    int value {42};
};


template <>
inline std::string Foo::get () const {
    return str;
}

template <>
inline int Foo::get () const {
    return value;
}

第二個是使用具有不同參數類型的輔助函數。

class Foo2 {
public:
    template <typename T>
    T get () const {
        return get_helper (typename std::is_same<T, std::string>::type {});
    }


private:
    std::string get_helper (std::true_type) const {
        return str;
    }

    int get_helper (std::false_type) const {
        return value;
    }

private:
    std::string str {"YYY"};
    int value {44};
};

第三種選擇是使用SFINAE。

class Foo3 {
public:
    template <typename T>
    typename std::enable_if<std::is_same<T, std::string>::value, T>::type get () const {
        return str;
    }

    template <typename T>
    typename std::enable_if<std::is_same<T, int>::value, T>::type get () const {
        return value;
    }

private:
    std::string str {"ZZZ"};
    int value {45};
};

用法如下:

template <typename T>
void show (T v) {
    std::cout << v << std::endl;
}

Foo f1;
show (f1.get<std::string> ());
show (f1.get<int> ());

Foo2 f2;
show (f2.get<std::string> ());
show (f2.get<int> ());

Foo3 f3;
show (f3.get<std::string> ());
show (f3.get<int> ());

當您想要區分兩種類型時,第二個選項很有用。 如果你有更多的吸氣劑,那么你可能需要使用第一個或第三個選項。

我認為最好為每個字段定義一個getter和setter。 這是一種更好的方法。 它更容易閱讀和理解,你實現與模板技術相同。


您的代碼說明:

由於類型檢查,它無法編譯。 在C ++ 11中使用時會生成模板函數。 您將它與模板參數string一起使用,以便生成該函數。 問題是你生成一個函數,它返回T作為一個string ,但你的函數中有代碼返回int (變量amin )。 如果T等於string ,則在腦海中生成函數:

string get_field(){
    if(is_same<string,string>::value)
        return pegah;                      // OK
    else if(is_same<string,int> ::value)
        return amin;                       // NOT OK, amin is of type int
}

一種解決方案是MM ,它被稱為專業化。 您專門為(a)特定參數設置模板。 還有其他答案即將出現。


我不建議這樣做,因為除了為專用模板中的每個變量生成getter函數之外,你最后什么都不做。 你也可以寫一下:

string get_pegah(){ return pegah; }
int get_amin() { return amin; }

更易於閱讀,維護和直接。 我覺得效率更高。


如你所見,我只想使用一個功能

你真的不是。 您可以調用get_field<string>get_field<int>並在調用時生成相應的函數; 使用T=stringT=int或兩者(取決於您的用例)。 雖然你現在已經學會了,但在這種情況下這樣做是錯誤的。

您可能意味着您希望有一個函數定義來執行您想要的操作。 我不認為這是可能的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM