[英]How to get the value of a template class?
我正在嘗試獲取模板 class 的值。要獲取 class 的值,我可以輕松地執行以下操作:
int get_value()
{
return *this;
}
但我想創建一個 class,並擴展它,並且不要在所有類中再次創建get_value()
。 所以,我這樣做了:
template<typename T>
class _extend : public T
{
public:
auto _get_value()
{
return *this;
}
};
template<typename T>
class extend : public _extend<T>
{
public:
T get_value()
{
auto value = this->_get_value(); /* It was `_get_value()`, changed to `this->_get_value()` due to the comments */
T output = value;
return output;
}
};
但它不起作用:output 什么都不是。
編輯
示例程序:
#include <iostream>
namespace kc
{
template<typename T>
class _extend : public T
{
public:
auto _get_value()
{
return *this;
}
};
template<typename T>
class extend : public _extend<T>
{
public:
T get_value()
{
auto value = this->_get_value();
T output = value;
return output;
}
};
class A : public std::string, public extend<std::string>
{
public:
using std::string::string;
};
}
int main()
{
kc::A a("a");
std::cout << a.get_value() << std::endl;
}
問題中代碼的問題是多個inheritance。 _extend<string>::get_value()
將被調用的*this
不是具有值的字符串。
盡管我同意@NicolBolas 在評論中的觀點,因為我不明白您為什么要這樣做,但是您可以制作一個 class 模板,該模板將僅返回一層 inheritance 的值。 您只需要給它一個完美的轉發構造函數並將get_value()
轉換為基本類型,即
#include <iostream>
#include <string>
namespace kc
{
template<typename T>
class extend : public T
{
public:
template<typename... Args>
extend(Args&&... args) : T(std::forward<Args>(args)...)
{}
T get_value()
{
return *static_cast<T*>(this);
}
};
}
int main()
{
kc::extend<std::string> a("foo");
std::cout << a.get_value() << std::endl;
}
基本上:
template<class C>
class extend : public C
{
public:
using C::C;
auto get()
{
return *this;
}
};
一個完整的例子:
#include <iostream>
template<class C>
class extend : public C
{
public:
using C::C;
auto get()
{
return *this;
}
};
class e_string : public extend<std::string>
{
public:
using extend<std::string>::extend;
};
int main()
{
e_string s = "Test";
std::cout << s.get() << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.